C# – the syntax to use C# generics as a constructor name

c++genericsinheritance

I've got a number of classes that inherit from Item<T>.

Each class has a Create() method that I would like to move up into Item<T>.

Yet the following code gets the error "Cannot create an instance of the variable type 'T' because it does not have the new() constraint":

T item = new T(loadCode);

What is the correction syntax to do this?

public abstract class Item<T> : ItemBase
{

    public static T Create(string loadCode)
    {
        T item = new T(loadCode);

        if (!item.IsEmpty())
        {
            return item;
        }
        else
        {
            throw new CannotInstantiateException();
        }
    }

Best Solution

It's not possible. You can only use new() constraint to force existence of a constructor.

A workaround is to take a Func<InputType, T> (Func<string,T> in your example) delegate as input parameter that'll create the object for us.

public static T Create(string loadCode, Func<string,T> construct)
{
    T item = construct(loadCode);

    if (!item.IsEmpty())
    {
        return item;
    }
    else
    {
        throw new CannotInstantiateException();
    }
}

and call it with: Item<T>.Create("test", s => new T(s));