J Fabian Meier
J Fabian Meier

Reputation: 35785

determine whether a generic type has a standard constructor

Let T be a generic type. I would like to do something like this:

T x = default(T);
if (T has standard constructor)
  x = new T();

Of course, one could restrict T to types having such a constructor, but I do not want ot exclude value types.

How can you do that?

Upvotes: 0

Views: 116

Answers (2)

Adam
Adam

Reputation: 15805

edit:

The question states that

Of course, one could restrict T to types having such a constructor, but I do not want not exclude value types.

Using the constraint shown below does not limit T to Reference types. If you need to support other constructors for a different reason, please update your question.


(pre-edit: may not apply to question after all)

You are looking for a new constraint (also referred to as a parameter-less constructor constraint):

class YourClass<T> where T : new()
{
    public T doSomething()
    {
        return new T();
    }
}

T is definitely allowed to be a value type, for instance:

YourClass<char> c = new YourClass<char>();
char result = c.doSomething();

Upvotes: 0

Steve Czetty
Steve Czetty

Reputation: 6228

You'll have to use reflection:

ConstructorInfo ci = typeof(T).GetConstructor(Type.EmptyTypes);
if (ci != null)
    x = (T)ci.Invoke(null);

You can also use Activator.CreateInstance<T>(), but that will throw an exception if the constructor doesn't exist.

Upvotes: 2

Related Questions