Static:
Static members can only be accessed within the static methods. The non-static methods cannot access static members.
Readonly:
Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor.
Constant:
Constant variables cannot be modified after declaration.
Example: static vs readonly vs const
public class Programing { public static void Main() { TheClass mc = new TheClass(50); mc.ChangeVal(45); mc.Display(); Console.WriteLine("TheClass.constvar = {0}", TheClass.constvar); Console.WriteLine("TheClass.staticvar = {0}", TheClass.staticvar); } } public class TheClass { public readonly int readonlyvar = 10, readonlyvar2; public const int constvar = 20; public static int staticvar = 0; public TheClass(int i) { readonlyvar2 = i; // valid //z = i; //compile-time error staticvar = i; // valid } public void ChangeVal(int val) { //x = val; //z = i; //compile-time error staticvar = val; // valid } public void Display() { Console.WriteLine(staticvar); Console.WriteLine(readonlyvar); Console.WriteLine(constvar); } }
Hope it will be helpful for you. Thanks for asking here.
Question and answer is powered by AnsPress.io