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?
A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is same as the class name. Constructors can be Generic, despite its class is not Generic.
A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.
If you want to initialize Generic object, you need to pass Class<T> object to Java which helps Java to create generic object at runtime by using Java Reflection.
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");
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With