mardi 6 juillet 2021

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?

Aucun commentaire:

Enregistrer un commentaire