I have encounter question on forum that "What is the difference between static readonly and cost fields ?" and after exploring about it, I prefer to share with you all.
Although the two fields are similar but the main difference between these type of fields are explain in sample code below:
public int variableH = 1;
public const int varibaleA = variableH; //Compile time error
public static readonly int variableB = variableH;
Fields declared const cannot be initialized by other variable, it need to be initialized by some constant value.
Like
public const int varibaleA = 0;
or
public const int varibaleC = 0;
public const int varibaleB = variableC;
However fields defined as static readonly can be initialized by other variable as shown resulting in successful compilation.
First thing,
ReplyDeleteA static readonly veriable will require another static variable for assignment.
Any static method or property requires static variables.
Another note , static const can be assigned with static const "variable",
the difference between static readonly and static cosnt variables is the assignment , in which you can assign static readonly a value even in the static constructor.
In short , you may able to change the value once at the start for readonly.