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

224
Vistas
C# Unexpected output from a singleton pattern class that is creating different instances at run time

I am learning design patterns. I created a singleton Logger class that should return an new instance of logger only if it is null, and return the same instance every time otherwise. But implementing the class is resulting in creating a new instance everytime.

public class Logger
{
    private Logger()
    {

    }

    private static Logger instance;

    public static Logger Instance
    {
        get
        {
            return instance == null ? new Logger() : instance;
        }
    }
}

static void Main ()
{
    Logger log1 = Logger.Instance;
    Logger log2 = Logger.Instance;

    Console.WriteLine(log1.GetHashCode());
    Console.WriteLine(log2.GetHashCode());
}

The resulting hashcode is supposed to be the same on both lines but its not. Why is that?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

public static Logger Instance
{
    get
    {
        return instance == null ? new Logger() : instance; // You do not _set_ 'instance' !
    }
}

So, this should be more like

public static Logger Instance
{
    get
    {
        if( instance is null ) instance = new Logger();
        return instance;
    }
}

Mind that this is not threadsafe.

About the correct and safe implementation of Singletons, there are many articles written by people that can do that way better than I ever could. I suggest you explore that a little.

over 4 years ago · Santiago Trujillo Denunciar

0

you must initialize the "instance" field with the new logger instance before returning it or it will always be null.

if (instance == null)
{
    instance = new Logger();
}
return instance;

you can also use a single expression

return instance == null ? (instance = new Logger()) : instance;

Note: in a multi-thread environment you need to use a lock or other synchronizations

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