C# – When is a ReadOnly Variable allocated


An online test has this question:

Features of Read Only Variable:

  1. It is allocated at compile time
  2. Declaration and initialization is separated
  3. It is allocated at runtime
  4. All of these

The test gave the answer as 4. I get 2 and 3 but not sure about 1. Would this be an example of when the answer of 1 could occur:

private readonly int readonlyExample = 10;

Note: I would normally use a const for the example above

Best Solution

If you assigned a value to readonly variable then you are binding variable then this is compile time. For example:

readonlt int xyz=10; // then this is compile time

If you are assigning value from any function that will execute and return value then it will be Run Time. For example:

readonly int xyz=objClass.getSum();  // Then it is runtime.