Static is a keyword, whereas Singleton is a design implementation. A programmer has the liberty to make the class either singleton or static, depending on the needs of the program. Each type offers key features, which is why you need to know the differences between them.
To create a static class, we use the static
keyword.
static class <classname> {}
There are some specific features of a static class:
new
keyword. To access the members and methods of a static class, write classname
followed by a period and then the name of the member or method.<classname>.<member/method>
static
keyword; otherwise, a compile-time error will be generated.using System;namespace StaticvsSingleton{// Class takes length and width as inputs// and tells if it is a rectangle or a squarestatic class RectangleOrSquare{// Method to evaluate whether it is a// Rectangle or a Squarepublic static void Evaluate(int length, int width){if (length == width){Console.WriteLine("It is a square");}else{Console.WriteLine("It is a rectangle");}}}class MyProgram{// Main methodstatic public void Main(){RectangleOrSquare.Evaluate(5, 9);RectangleOrSquare.Evaluate(6, 6);}}}
To create a singleton class, you need to instantiate an instance inside the class and create a method to return the same instance every time the class object is called. Since the instance remains the same throughout the program, we use the static
keyword.
static <classname> <instance name> = new <classname>()
public static getInstance
{
get {return <instance name> }
}
There are some specific features of a singleton class:
using System;namespace StaticvsSingleton{// Class takes length and width as inputs// and tells if it is a rectangle or a squareclass RectangleOrSquare{// Instantiating singleton classstatic RectangleOrSquare Instance = new RectangleOrSquare();// Private constructorprivate RectangleOrSquare(){}// Method to retrive the singleton instancepublic static RectangleOrSquare getInstance{get{return Instance;}}// Method to evaluate whether it is a// Rectangle or a Squarepublic void Evaluate(int length, int width){if (length == width){Console.WriteLine("It is a square");}else{Console.WriteLine("It is a rectangle");}}}class MyProgram{static public void Main(){// You can access singleton class in two ways// Method 1RectangleOrSquare.getInstance.Evaluate(5, 9);RectangleOrSquare.getInstance.Evaluate(6, 6);// Method 2RectangleOrSquare thisInstance = RectangleOrSquare.getInstance;thisInstance.Evaluate(5, 9);thisInstance.Evaluate(6, 6);}}}
Free Resources