0

I have a problem regarding the usage of instances in C#. Can you please explain me the difference between the following 2 code lines:

public static DatabaseClass Instance { get; } = new DatabaseClass();

DatabaseClass _database = DatabaseClass.Instance;
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 1
    The first one is a public property, that cannot be changed from outside the class. The second one is a private (by default) field that refers to code that you haven’t included in your question, `DatabaseClass.Instance` ..? – stuartd Mar 28 '21 at 20:04
  • Looking at those two lines it seems `DatabaseClass` is a singleton – C.Evenhuis Mar 28 '21 at 20:18
  • See the singleton pattern and its Lazy implementation. https://csharpindepth.com/articles/singleton – Amir Mar 28 '21 at 21:04
  • @Amir Don't get her confused. Singleton can be implemented in many different ways and all singletons are lazy by definition. None get initialized before the first call. There is no real need to use `Lazy` in singleton. – T.S. Mar 28 '21 at 21:11
  • The first implementation is not Lazy dear ;-). Visit the link again. Thanks for your notes. – Amir Mar 28 '21 at 21:22
  • Thank you so much, I understood the meaning – Angela Raveendraraj Mar 29 '21 at 05:54

1 Answers1

1

The biggest difference is that this is declaration

public static DatabaseClass Instance { get; } = new DatabaseClass();

and this is usage

DatabaseClass _database = DatabaseClass.Instance;

You took 2 lines of code out of context. The true context is the classes that have these lines in. One class is most likely a Singleton

public class DatabaseClass 
{
    private DatabaseClass() {} // hide constructor

    public static DatabaseClass Instance { get; } = new DatabaseClass();
}

And another class has some method that calls the class above

public class SomeClass
{
    public static void DoSomething()
    {
        DatabaseClass _database = DatabaseClass.Instance;
        _database.PerformSomeOperation()
    }
}

By simply looking at the declaration, it is a common way to deal with singletons.

For your question the bottom line is that

line#1 is a declaration of the static property with default read-only value

line#2 is usage of that property

T.S.
  • 18,195
  • 11
  • 58
  • 78