Thursday, November 12, 2009

Difference between const and readonly

The readonly keyword is different from the const keyword.

A const field can only be initialized at the time of declaration. It specifies that the value of the field or the local variable cannot be modified.
A readonly field or variable can be initialized either at the declaration or in a constructor in the same class. Therefore, readonly variable or fields can have different values depending on the constructor used. A static readonly field can be set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.

A const field is a compile-time constant.
A readonly field is a runtime constant.

using System;

public class Test
{
public const int rows = 10; // Initialize a const field
public const int seats = rows + 25;
public const double size = 5.0, width = 72.5, height = 44.45;

public readonly int x = 30; // Initialize a readonly field
public readonly int y;

public Test()
{
y = 100; // Initialize a readonly instance field
}

public Test(int a, int b)
{
x = a;
y = b;
}
}

No comments: