9

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?

3 Answers 3

11

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");
}
Sign up to request clarification or add additional context in comments.

3 Comments

So if the (string) constructor doesn't exist, it'll be a runtime error?
@Smashery: Exactly. It will throw an exception if T doesn't have a public (string) constructor.
Thanks very much! Sucks I can only pick one "correct answer", but thanks for teaching me something new!
8

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));

1 Comment

The method signature gets a lot more complicated than dtb's solution, but I do like the compile-time checking that comes with it. Trade-offs, I guess.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.