What
is the difference between const and readonly in .NET?
The programmer
want to link together pages with previous and next page functionality,
you had to insert link manually for this to work. Whenever a page was
added or inserted, you had to adjust links in two more files.
Const
ReadOnly
Value
of const identifiers cannot be changed.
User
cannot change value of ReadOnly identifiers but they can be changed
by themselves.
Const
identifiers are static members by default. Here is an example defining
and using Const:
public class sampleClass{
public const int sample = 10;
public static void Main() {
Console.WriteLine("sampleClass.sample
is {0}", sampleClass.sample);
}
}
Output of this code will be:
sampleClass.sample is 10
In the above example, if you try to access sample using an instance
of sampleClass named obj, then you will get the following error:
Static member 'sampleClass.sample' cannot be accessed with an instance
reference; qualify it with a type name instead
Readonly
identifiers are instance members.
Here is an example for readonly:
public class sampleClass{
public readonly int sample = 10;
public static void Main() {
sampleClass obj = new
sampleClass();
Console.WriteLine("obj.sample is {0}",
obj.sample);
}
}
Output of this code will be:
obj.sample is 10
You will get the following error if you try to access sample as sampleClass.sample:
An object reference is required for the nonstatic field, method, or
property 'sampleClass.sample'
Const
identifiers are compile time constants. They cannot be initialized
at run time.
ReadOnly
identifiers are run time constants. They can be initialized inside
constructor of the class during run time.