Const
Let's us look at an example.
Example 1
- namespace Sample {
- public class MyClass
- {
- private const int a;
-
- }
- public class Sample2
- {
- static void Main()
- {
- }
- }
- }
Output
A const variable must be initialized when declared and can't be modified later.
- Private static const int a=9;
Example 2
- namespace Sample
- {
- public class Sample1
- {
- private const Sample2 sample2 = new Sample2();
-
- }
- public class Sample2
- {
-
- }
- public class Sample3
- {
- static void Main()
- {
- }
- }
- }
Output
A const field of a reference type other than string can only be initialized with null.
Example 3
- namespace Sample
- {
- public class Sample1
- {
- private const Sample2 sample2 = null;
-
- }
- public class Sample2
- {
-
- }
- public class Sample3
- {
- static void Main()
- {
- }
- }
- }
Output
Example 4
- namespace Sample
- {
- public class Sample1
- {
- public const int a = 1;
- public const int b = b + 2;
- }
- public class Sample3
- {
- static void Main()
- {
- }
- }
- }
The value of b evaluates at compile time, a constant can participate in a constant expression.
Static Field
Example 1
- namespace Sample
- {
- public class Sample1
- {
- public static int c1;
- static void Main()
- {
- Console.WriteLine(c1);
- Console.ReadKey();
- }
- }
- }
Output
Static variables are initialized as soon as the class loads with the default value. A variable in C# can never have an uninitialized value.
ReadOnly
- namespace Sample
- {
- public class Sample1
- {
- public static readonly int a=8;
- static void Main()
- {
- a = 10;
- Console.WriteLine(a);
- Console.ReadKey();
- }
- }
- }
Output
Error 1 A static readonly field cannot be assigned to (except in a static constructor or a variable initializer).
A Readonly field can be declared either when it is declared or in the constructor of its class.
Difference between const and Readonly keyword
A const field can only be initialized in the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. A const field is a compile-time constant. A readonly field can be used for runtime constants.
- namespace Sample
- {
- public class Sample1
- {
- public readonly int _a;
- public Sample1(int a)
- {
- _a = a;
- }
- static void Main()
- {
- Sample1 sample = new Sample1(5);
-
- Console.WriteLine(sample._a);
- Console.ReadKey();
- }
- }
- }
Output