C#
offers the const
keyword to define variables with a fixed, unalterable value (constant
data). Once the value of a constant has been established, it can
never change, and any attempt to alter it results in a compiler
error.
Note:
The declaration and initialization of a constant field must
be simultaneous. This is because of the fact that the
value of constant data must be known at compile time.
Ex:
class
MyMathClass
{
public
const double PI = 3.14;
}
class
Program
{
static
void Main(string[] args)
{
Console.WriteLine("The
value of PI is: {0}", MyMathClass.PI);
}
}
Notice
that the
constant data defined by MyMathClass
is referenced using
a class name prefix (i.e., MyMathClass.PI).
This is due to the fact that constant fields of a class are
implicitly static.
The value assigned to a constant variable must be known at compile time, and therefore a constant member cannot be assigned to an object reference (whose value is computed at runtime). Constant fields are implicitly static. However, it is permissible to define and access a local constant variable within a type member.
The value assigned to a constant variable must be known at compile time, and therefore a constant member cannot be assigned to an object reference (whose value is computed at runtime). Constant fields are implicitly static. However, it is permissible to define and access a local constant variable within a type member.
Ex:
static
void LocalConstStringVariable()
{
//
A local constant data point can be directly accessed.
const
string fixedStr = "Fixed string Data";
Console.WriteLine(fixedStr);
}
Unlike
in C++, in
C# the const keyword cannot be used to qualify parameters or return
values,
and is reserved for the creation of local or instance-level data.
Related
Post:
Read
Only Fields in C#
No comments:
Post a Comment