Question

here is two piece of class code one is for Singleton and other one is for static class. i like to understand in programming when one should use static class and when one should use Singleton class?

both are used to hold the global object as a result we can access those data from any where of the program when it is running. scope is broad for both....the life time of application.

1) i really do not find any article which can guide me when i should use static class and when Singleton class should be good choice. i have seen people manage db connection using Singleton class.

2) what is the main difference between Singleton class & static class ?

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

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

public static class TestStatic //: ITestSingleton
    {
        public static void doAction(string args)
        {
            Console.WriteLine("Test Static :: " + args);
        }
    } 
Was it helpful?

Solution

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

Use singleton when you need a class that has only one instance, and you need to provide a global point of access to the instance

OTHER TIPS

A singleton is basiccly an entry point to a single instance of a class. The instance of that class can be passed to another method as a reference.

A static class doesn't have this behaviour (only static methods are allowed).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top