Frequently Asked Interview Questions

const vs readonly Variables in C#

Constant VariablesReadonly Variables
1. value evaluated at compile time1. Value evaluated at run time.We can assign values to readonly variables in constructor.
2. constants are declared with the const keyword.
public const int Millennium = 2000;
2. declared with readonly keyword.
Public readonly int year =2010;
3. Const Variables Can also declared inside methods.3. Read-only variables cannot be declared with method scope.
4. Value is constant for all objects.4. Each object can have different value to readonly variable, but once we assign a value in constructor it can not be modified.
5. can be used only for primitive types (built-in integral and floating-point types), enums, or strings.We cannot initialize a constant variable using the new operator.
// Does not compile:
private const DateTime classCreation = new DateTime(2000, 1, 1, 0, 0, 0);
5. Read-only values are also constants, in that they cannot be modified after the constructor has executed. But read-only values are different in that they are assigned at runtime.
// Works here:
private const DateTime classCreation = new DateTime(2000, 1, 1, 0, 0, 0);


The most important distinction is that readonly values are resolved at runtime. The IL generated when you reference a readonly constant referencesthe readonly variable, not the value. Compile-time constants generate the same IL as though you’ve used the numeric constants in your code, even across assemblies: A constant in one assembly is still replaced withthe value when used in another assembly.

Suppose you have defined both const and readonly fields in an assembly named Infrastructure:


public class UsefulValues
{
public static readonly int StartValue = 5;
public const int EndValue = 10;
}


In another assembly, you reference these values:

for (int i = UsefulValues.StartValue;i < UsefulValues.EndValue; i++)

Console.WriteLine("value is {0}", i);


If you run your little test, you see the following obvious output:
Value is 5
Value is 6
...
Value is 9

Time passes, and you release a new version of the Infrastructure assembly
with the following changes:

public class UsefulValues
{
public static readonly int StartValue = 105;
public const int EndValue = 120;
}

You distribute the Infrastructure assembly without rebuilding your Application assembly.

You expect to get this:
Value is 105
Value is 106
...
Value is 119

In fact, you get no output at all. The loop now uses the value 105 for its
start and 10 for its end condition. The C# compiler placed the const value
of 10 into the Application assembly instead of a reference to the storageused by EndValue.

Most Visited Pages

Home | Site Index | Contact Us