Usage of Activator.CreateInstance()

463 Views Asked by At

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();
1

There are 1 best solutions below

1
Aron On

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).