Hey Itsme
Hey Itsme

Reputation: 61

Usage of Activator.CreateInstance()

What is actually the difference between the below two code snippets?

Object o = Activator.CreateInstance(typeof(StringBuilder));

StringBuilder sb = (StringBuilder) o;

and

StringBuilder sb = new StringBuilder();

Upvotes: 2

Views: 528

Answers (1)

Aron
Aron

Reputation: 15772

From a practical point of view. There is no difference.

However, from a technical point of view. The first will incur a substantial performance penalty.

First, from the Activator.CreateInstance, since this is a Reflection call.

Then another performance hit when you cast object to StringBuilder.

From a design point of view however. Activator.CreateInstance takes Type as a parameter...

This means you can do the following...

public IStringBuilder ActivateStringBuilder(Type builderType)
{
     return (IStringBuilder) Activator.CreateInstance(builderType);
}

Ignoring that there is no such thing as IStringBuilder the above code allows you to, at runtime, change the behavior of the code, by passing in different Types that implement IStringBuilder.

This is the basis for Dependency Injection (although, we tend to use much more complicated mechanisms to get around the performance issues I pointed out).

Upvotes: 4

Related Questions