Constant->static and readonly->instance field in C#

There are 2 options for the developers to declare a constant value in their C# application.
1. readonly
2. const

If you need to initialize a constant field at runtime , you must use readonly instead of const. const fields can only be initialized at compile time i.e they must be assigned a value at the time of declaration. You cannot modify it after its declaration.

The readonly fields can be either initialized at the time of declaration and/or within the constructor of the class. This means that you can initialize it at runtime (only within the constructor.

public class Student
{
    public readonly int age = 0;
    public const int marks = 0;

    public Student(int id, int age, int marks)
    {
        // You can assign the value for readonly field in the constructor
        this.age = age;

        // You cannot assign the value in the constructor for const field
        //this.marks = marks;
    }
}

When you verify the IL code that is getting generated for the const and readonly fields , you will notice that by default the const field is compiled to static field where as the readonly field is compiled to instance field.

image

Hence , you can access the const field using just the class name like the way you access a static field.

Console.WriteLine(Student.marks)

Leave a Reply