Vijjendra Vijjendra - 16 days ago 4
ASP.NET (C#) Question

How to access Singleton class's static method?

I have some confusion with singleton class, below are my some points:


  1. Can singleton class have static method?,if yes then how we call that methods?

  2. what is main difference between Static class and Singleton Class?



I have created my singleton class as follows:

public class Singleton
{
private static Singleton _instance = null;
private static object chekLock = new object();
private Singleton()
{}

public static Singleton Instance
{
get
{
lock (chekLock)
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
}

public static void StaticAddMethod()
{
Console.WriteLine("Add Method");
}

public void AddMethod()
{
Console.WriteLine("Add Method");
}
}


In Above class structure I have created two method one is Static and second is non static, When I am trying to access Static Method it gives me compile time error.

How can I use static method of singleton class?

Answer

How are you trying to access it? To access a static method you use the type name:

Singleton.StaticAddMethod();

vs

Singleton.Instance.AddMethod();

Note also that there are simpler ways of implementing singletons that acheive the same effect with less locking etc.

Re the difference between singleton and static; a singleton might implement an interface, allowing you to pass it into existing code. You can also (as indeed you are doing) defer construction of a singleton (yet still allow access to the static methods that don't involve the singleton instance). But yes: there is a lot of crossover between static and singleton.