code_junkie

Creating a new instance of n mostly unknown type

Nov 13th, 2011
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.53 KB | None | 0 0
  1. protected T CreateNew<T>()
  2. where T : new()
  3. {
  4. return new T();
  5. }
  6.  
  7. var x = CreateNew<Point>();
  8.  
  9. ISomeInterface inter;
  10. if (selection == 1)
  11. inter = new SomeClass();
  12. else
  13. inter = new SomeClass2();
  14. // ...
  15. ISomeInterface inter2 = CreateNew<typeof(inter)>();
  16.  
  17. Function<ISomeInterface> creationDelegate;
  18. if (selection == 1)
  19. creationDelegate = () => CreateNew<SomeClass>;
  20. else
  21. creationDelegate = () => CreateNew<SomeClass2>;
  22. ISomeInterface inter = creationDelegate();
  23.  
  24. // ...
  25. ISomeInterface inter2 = creationDelegate();
Add Comment
Please, Sign In to add comment