Difference between Static and Singleton ?


Difference between Static and Singleton ?

Static 


Example -

public static class StaticClass
    {
        static StaticClass()
        {
           
        }
        private static string studentName;
        public static string GetStudentName()
        {
            return studentName;
        }
    }

1. Static object stores in stack because it can’t be instantiated and don’t have any reference.

2. Static class can have only static methods and static variables.

3. Static class cannot have pubic constructors in C#.

4. It is not possible to create Instance of static class.

5. Static class can’t be pass to a method.

6. One Static class cannot inherit another Static in c#.

7. Static class members cannot be serialized.

8. Lazy initialization not supported in Static Class because everything loaded when class loaded.

9. Static Class not follow the OOP (Object Oriented Programming).


Singleton


Example

    public class SingletonClass
    {
        private static SingletonClass instance;
        private SingletonClass() { }
        public static SingletonClass Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SingletonClass();
                }
                return instance;
            }
        }
    }

1. Singleton object stores in Heap.

2. In Singleton, instance is created first time after that instance reuse again and again.

3. Singleton class can have constructor.

4. Singleton instance can be pass to a method.

5. Inheritance supported by Singleton Class and you can implement Interface in Singleton Class

6. We can dispose the objects of a singleton class.

7. Singleton is not thread safe.

8. Methods can be overridden.

9. Lazy initialization supported by Singleton and can be lazy loaded when needed.

10. Singletons are easier to work with when unit testing a class.

11. Singleton class follow the OOP (Object Oriented Principles).

12. Factory Pattern use to create instance of Singleton Class.

13. You can maintains states in Singleton class.



Keywords - 

Difference between Singleton Class and Static Class 

Singleton vs Static

Singleton Class vs Static Class


Comments