Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new instance of T without the new constraint

If one wants to create a new instance of a generic, the new constraint needs to be defined, like so:

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

Is it possible, using reflection, to create an instance of T without the new constraint, like so (contains pseudocode):

public T SomeMethod<T>()
{
    if (T has a default constructor)
    {
        return a new instance of T;
    }
    else
    {
        return Factory<T>.CreateNew();
    }
}
like image 619
Dave New Avatar asked Jun 26 '13 06:06

Dave New


People also ask

What is new () constraint in C#?

The new constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

What is the function of the not new constraint?

2. What is the function of the not null constraint? Explanation: The not null constraint ensures that data is entered into the database. It displays an error message whenever a data field mentioned is left empty.

How do I create a new generic class in C#?

You can create your own generic classes, methods, interfaces and delegates. You can create generic collection classes. The . NET framework class library contains many new generic collection classes in System.


2 Answers

Use Activator.CreateInstance() for this. See http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx for more information on how to use this method. Basically, what you do is:

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

You can verify whether it has a default constructor by using the GetConstructors() method:

var constructors = typeof(T).GetConstructors();

If you find a constructor that has zero parameters, you can use the Activator.CreateInstance method. Otherwise, you use the Factory<T>.CreateNew() method.

EDIT:

To find out directly whether a constructor without any parameters exist, you can use the following check:

if (typeof(T).GetConstructor(Type.EmptyTypes) != null)
{
    // ...
like image 196
Pieter van Ginkel Avatar answered Oct 27 '22 02:10

Pieter van Ginkel


Generic methods with a where T : new() constraint implement new T() calls by invoking Activator.CreateInstance<T>(). One interesting thing about this method is that it doesn't include the constraint, so if you are happy to defer the check until runtime, just use:

public T SomeMethod<T>() {
    return Activator.CreateInstance<T>();
}

which will either do exactly what return new T() would have done, or will raise a meaningful exception. Because it handles both the success and failure case, there is no real benefit in doing any additional checks, unless you wanted to do something obscure like not using a constructor at all (which can be done).

like image 28
Marc Gravell Avatar answered Oct 27 '22 03:10

Marc Gravell