NibblyPig
NibblyPig

Reputation: 52932

Is there a noticible difference between Activator.CreateInstance and using expressions?

With this code:

public static class ChocolateFactory<T>
{
    private static Func<int, int, T> Func { get; set; }

    static ChocolateFactory()
    {
        ChocolateFactory<EmergencyChocolate>.Func = (a, b) => new EmergencyChocolate(a, b);
    }

    public static T CreateChocolate(int a, int b)
    {
        return (T)Activator.CreateInstance(typeof(T), a, b);
        //return ChocolateFactory<T>.Func(a, b);
    }
}

If I run:

var myChocolate = ChocolateFactory<EmergencyChocolate>.CreateChocolate(1, 2);

Is there a significant difference between the two methods of creation (one is commented out)? Activator is much cleaner code-wise but I understand it can be slower, but I am wondering if I'm overlooking anything else. I'm also wondering if anything here is pre-compiled.

Also, what is the name of the methodology here if not using Activator?

Upvotes: 2

Views: 110

Answers (2)

xanatos
xanatos

Reputation: 111860

There is no static checking if you use Activator.CreateInstance. The compiler can't check if there is a public constructor with two int parameters.

And it's probably slower because it uses reflection.

Upvotes: 7

dustinmoris
dustinmoris

Reputation: 3361

With the activator class you can generate an instance of any type, by having only one method.

With your factory method you can only create an instance of one class and for a different class you would have to create a different factory method.

Activator is not cleaner than the other. It depends what you want to do. An IoC container typically uses Activator, because it can't create factory methods for all your classes, because it simply doesn't know what you've got.

Upvotes: 0

Related Questions