Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Smashery Avatar asked Nov 22 '10 23:11

Smashery


People also ask

Can you make a generic constructor?

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.

Does a generic class need a constructor?

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.

How do you initialize a generic object in Java?

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.


2 Answers

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");
}
like image 100
dtb Avatar answered Oct 22 '22 16:10

dtb


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));
like image 34
JaredPar Avatar answered Oct 22 '22 15:10

JaredPar