Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!