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?
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");
}
(string) constructor doesn't exist, it'll be a runtime error?T doesn't have a public (string) constructor.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));