Introduction
In this article we will learn about the difference between readonly, static and constant. Where to use static , constant and readonly with example.
Static modifier or keyword used to declare a static member, which belongs to its class rather than a specific object. A constant is implicitly a static member.The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
The following class is declared as static and contains only static methods:
static class MyClass
{
public static int x;
public static int y;
public static void disp()
{
x = 20;
y = 40;
Console.WriteLine("Value of x={0} and y={1}", x, y);
}
}
|
If the static keyword is applied to a class, all the members of the class must be static.
Static constructor can't be parameterized. Access modifiers can not be applied on Static constructor.Static constructor always public by default.
Readonly field can be initialized either at the declaration time or with in the same class constructor.Therefore, readonly fields can be used for run-time constants.
class MyClass
{
readonly int X = 20; // initialized at the time of declaration
readonly int Y;
public MyClass(int y)
{
Y = y; // initialized at run time
}
} |
Readonly keyword can be apply to reference type and value type both. But delegate and event could not be readonly.
Constant fields must be assigned a value at the declaration time and after that they cannot be modified (can not changed). By default constant are static, hence you cannot define a constant type as static.
void Calculate(int x)
{
const int X = 10, Y = 50;
const int Z = X + Y; //no error, evaluated at compile time.
const int P = X + x; //gives error, evaluated at run time.
} |
0 comments:
Post a Comment