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();
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();
Copyright © 2021 Jogjafile Inc.
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
objecttoStringBuilder.From a design point of view however.
Activator.CreateInstancetakesTypeas a parameter...This means you can do the following...
Ignoring that there is no such thing as
IStringBuilderthe above code allows you to, at runtime, change the behavior of the code, by passing in differentTypes that implementIStringBuilder.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).