Smashery
Smashery

Reputation: 59653

Constructing a Generic object (not default constructor)

I am wanting to construct an object from within a generic method. This object takes a string in its constructor. Something like this:

public T GetObject<T>()
{
    return new T("Hello");
}

Is this possible?

Upvotes: 9

Views: 2900

Answers (3)

JaredPar
JaredPar

Reputation: 754575

One option is to rewrite this to force the caller to pass in a factory method / lambda

public T GetObject<T>(Func<string,T> func) 
{ 
  return func("Hello");
} 

The call site would be modified to look like this

GetObject(x => new T(x));

Upvotes: 8

Aliostad
Aliostad

Reputation: 81660

No. At the moment you cannot use parameterised constructors with generic types since you cannot define them in where.

Using Activator is not the same - and I believe not the answer to your question - but you can use it of course.

Upvotes: 0

dtb
dtb

Reputation: 217263

Yes, but only without compile-time checking if the constructor really exists: Activator.CreateInstance

public T GetObject<T>()
{
    return (T)Activator.CreateInstance(typeof(T), "Hello");
}

Upvotes: 11

Related Questions