Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda