In this post we are going to see what is the difference between Static Variable and Static read only variable in C#, For this to check we are taking a singleton class which can be very useful to discuss.
For Singleton we need a static variable for maintain the singleton instance. Let we see two classes one with static variable another one with static readonly
Static : Static constructor, Normal constructor, properties etc
Static Read Only : Static constructor, other places we can see the Error if user assign
Static :
**********************
In Static variable we can assign the value in static constructor, normal constructor, inside properties etc
Static Read only:
*********************
In static readonly we can assign the value only inside of the static constructor, other ways are not allowed.
}
From this post you can see what is the difference between static and static read only variable
For Singleton we need a static variable for maintain the singleton instance. Let we see two classes one with static variable another one with static readonly
Static : Static constructor, Normal constructor, properties etc
Static Read Only : Static constructor, other places we can see the Error if user assign
Static :
**********************
In Static variable we can assign the value in static constructor, normal constructor, inside properties etc
public class PlanetarySystem
{
private static PlanetarySystem _instance;
static PlanetarySystem()
{
_instance = new PlanetarySystem();
}
public PlanetarySystem(){
}
public static PlanetarySystem Instance
{
get
{
_instance = new PlanetarySystem();
return _instance;
}
}
public string
PlanetName { set; get; }
public int Rotation
{ set; get; }
public void Rotate()
{
Console.WriteLine("Rotating ... ");
}
}
Static Read only:
*********************
In static readonly we can assign the value only inside of the static constructor, other ways are not allowed.
public class PlanetarySystem
{
private static readonly PlanetarySystem _instance;
static PlanetarySystem()
{
_instance = new PlanetarySystem();
}
public PlanetarySystem(){
}
public static PlanetarySystem Instance
{
get
{
return _instance;
}
}
public string
PlanetName { set; get; }
public int Rotation
{ set; get; }
public void Rotate()
{
Console.WriteLine("Rotating ... ");
}
From this post you can see what is the difference between static and static read only variable