Constant and readonly fields are used to store constant data.

A constant field can only be initialized at the declaration of the
field.This means this can be initialized at the time of development
andby programmer only.

A readonly field can be initialized either at the declaration or in
a constructor. Hence , readonly fields can have different values
depending on the constructor used.

Example is given below :-

readonly int readonlyfield;
public X()
{
readonlyfield = 1;
}

public X(string s)
{
readonlyfield = 5;
}

public X(string s, int i)
{
readonlyfield = i;
}

Constant field is a compile-time constant, the readonly field can be used for runtime constants.

Advertisements