Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More trivia than really important: Why no new() constraint on Activator.CreateInstance<T>()?

I think there are people who may be able to answer this, this is a question out of curiosity:

The generic CreateInstance method from System.Activator, introduced in .NET v2 has no type constraints on the generic argument but does require a default constructor on the activated type, otherwise a MissingMethodException is thrown. To me it seems obvious that this method should have a type constraint like

Activator.CreateInstance<T>() where T : new() {
   ...
}

Just an omission or some anecdote lurking here?

Update

As pointed out, the compiler does not allow you to write

private T Create<T>() where T : struct, new()
error CS0451: The 'new()' constraint cannot be used with the 'struct' constraint

However, see comments a struct can be used as type argument to a generic method specifying a new() constraint. Under this circumstance the given answer seems the only valid reason to not constrain the method...

Thanks for looking over this!

like image 686
flq Avatar asked Mar 03 '11 23:03

flq


1 Answers

I could be wrong, but the main benefit as I see it is that it allows you to do something like this:

// Simple illustration only, not claiming this is awesome code!
class Cache<T>
{
    private T _instance;

    public T Get()
    {
        if (_instance == null)
        {
            _instance = Create();
        }

        return _instance;
    }

    protected virtual T Create()
    {
        return Activator.CreateInstance<T>();
    }
}

Note that if Activator.CreateInstance<T> had a where T : new() constraint, then the Cache<T> class above would also need that constraint, which would be overly restrictive since Create is a virtual method and some derived class might want to use a different means of instantiation, such as calling a type's internal constructor or using a static builder method.

like image 113
Dan Tao Avatar answered Nov 04 '22 11:11

Dan Tao