.net - C# Create New T()

ID : 20189

viewed : 25

Tags : c#.netgenericsc#-4.0.net-4.0c#

Top 5 Answer for .net - C# Create New T()

vote vote

100

Take a look at new Constraint

public class MyClass<T> where T : new() {     protected T GetObject()     {         return new T();     } } 

T could be a class that does not have a default constructor: in this case new T() would be an invalid statement. The new() constraint says that T must have a default constructor, which makes new T() legal.

You can apply the same constraint to a generic method:

public static T GetObject<T>() where T : new() {     return new T(); } 

If you need to pass parameters:

protected T GetObject(params object[] args) {     return (T)Activator.CreateInstance(typeof(T), args); } 
vote vote

86

Why hasn't anyone suggested Activator.CreateInstance ?

http://msdn.microsoft.com/en-us/library/wccyzw83.aspx

T obj = (T)Activator.CreateInstance(typeof(T)); 
vote vote

74

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args) {     return (T)typeof(T).GetConstructor(signature).Invoke(args); } 
vote vote

68

The new constraint is fine, but if you need T being a value type too, use this:

protected T GetObject() {     if (typeof(T).IsValueType || typeof(T) == typeof(string)) {         return default(T);     } else {        return (T)Activator.CreateInstance(typeof(T));     } } 
vote vote

56

Just for completion, the best solution here is often to require a factory function argument:

T GetObject<T>(Func<T> factory) {  return factory(); } 

and call it something like this:

string s = GetObject(() => "result"); 

You can use that to require or make use of available parameters, if needed.

Top 3 video Explaining .net - C# Create New T()

Related QUESTION?