How to access a const value without defining a static Class in C#?
In php I can define a Class with const value that can be easily accessed, how do I do that in C#?
<?php
class MyClass
{
const CONSTANT = 'constant value';
}
echo MyClass::CONSTANT;
The php class can be a general class, but has it to be a static Class in C# to get the same function??
A const
variable by its very nature is a static value. That is why when you declare a constant in a class, you cannot declare a constant as static
because it is already implicitly static.
public class Values
{
public const int CONSTANT_VALUE = 12;
}
Accessing a constant is done the same way you access a static field.
int i = Values.CONSTANT_VALUE;
The limitation of const
, however, is that it can only be used with value types. That's because when the program is compiled, the constant is actually turned into a literal value wherever it is referenced. After program is compiled, the above access to the constant gets essentially converted to this:
int i = 12;
Now just because a const
field is implicitly static doesn't mean it can only be declared in a static class. A static class is just a specialized class that contains no instance members. A regular class can hold both static and instance members.
public class Values
{
public const int CONSTANT_VALUE = 12;
public int Val;
}
This class can be used as such:
Values v = new Values;
v.Val = Values.CONSTANT_VALUE;