What is Const in C#?
Let's look at an example.
Example 1
namespace Sample
{
public class MyClass
{
private const int a;
}
public class Sample2
{
static void Main()
{
}
}
}
A const variable must be initialized when declared and can't be modified later.
private static readonly int a = 9;
Example 2
namespace Sample
{
public class Sample1
{
// You cannot initialize a constant with a new instance of Sample2
// private const Sample2 sample2 = new Sample2(); // Error
// If you want a read-only field, use 'readonly' instead
private readonly Sample2 sample2 = new Sample2();
}
public class Sample2
{
}
public class Sample3
{
static void Main()
{
}
}
}
A const field of a reference type other than string can only be initialized with null.
Example 3
namespace Sample
{
public class Sample1
{
// You can initialize a constant with 'null'
private const Sample2 sample2 = null;
}
public class Sample2
{
}
public class Sample3
{
static void Main()
{
}
}
}
Example 4
namespace Sample
{
public class Sample1
{
public const int a = 1;
public const int b = a + 2; // You can use 'a' here since it's a constant
}
public class Sample3
{
static void Main()
{
}
}
}
The value of b evaluates at compile time, a constant can participate in a constant expression.
Static Field in C#
Example 1
using System;
namespace Sample
{
public class Sample1
{
public static int c1;
static void Main()
{
Console.WriteLine(c1);
Console.ReadKey();
}
}
}
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 keyword in C#
using System;
namespace Sample
{
public class Sample1
{
public static readonly int a = 8;
static void Main()
{
// Error: You cannot assign a new value to a readonly field
// a = 10;
Console.WriteLine(a);
Console.ReadKey();
}
}
}
A Readonly field can be declared either when it is declared or in the constructor of its class.
Difference between const and Readonly keyword in C#
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.
using System;
namespace Sample
{
public class Sample1
{
public readonly int _a; // 'readonly' field can be assigned in the constructor
public Sample1(int a)
{
_a = a;
}
static void Main()
{
Sample1 sample = new Sample1(5);
Console.WriteLine(sample._a);
Console.ReadKey();
}
}
}