Reputation: 1
In the book C# in a Nutshell, constants are defined as a "static field" whose can never change, and in the code below, it is obvious that they behave like static fields.
public class Test
{
public const string Message = "Hello World";
}
static void Main()
{
Console.WriteLine(Test.Message);
}
It's a written message with the class name itself. But Constants can also be declared local to a method. For example:
static void Main()
{
const double twoPI = 2 * System.Math.PI;
}
And we can not declare a static field to a method, it is a compile-time error. So constants are static fields or not? And how CLR implement them?
Upvotes: 0
Views: 1096
Reputation: 82474
A const in c# is simply a named value.
The c# compiler simply replaces the const with it's value anytime it appears is the code.
Having said that, it does behave a little bit different when used as a field than it is when used as a local const.
When a a field is a const value, it can be accessed by other classes as if it was a static readonly field/property - but it is compiled as the hard coded value it represents in the calling class. Taking the example from the question:
public class Test
{
public const string Message = "Hello World";
}
// When the c# code containing the Main() method is compiled,
// it replaces Test.Message with "Hello World".
static void Main()
{
Console.WriteLine(Test.Message);
}
This means that if you have a public const field, and other classes are calling it, if you ever change the const field value, you would have to recompile all projects that have classes using that const field, otherwise they would still be using the old value (since it's now hard coded in their compiled code.
A local const acts much the same way, with the exception of not being accessible by other classes, or even by other parts of the same class, since it's local. Again, using the code from the question:
static void Main()
{
const double twoPI = 2 * System.Math.PI;
// The rest of Main code goes here
}
The twoPI
const is only accessible inside the Main()
static method in this example.
The c# compiler will replace the twoPI
with it's hard coded value any time you use it.
This is useful when you want to make sure you are using the same value throughout the entire scope it was defined - or when the value is less readable then a local const descriptive name.
Upvotes: 2