Reputation: 325
I want this approach.
const public int x;
at runtime
x = 10; //this value will change it another Class --> (Not internal)
x--> never change
is that possible any ways?
Upvotes: 6
Views: 13807
Reputation: 4298
You cant assign value to const variable at runtime but still you can achieve your requirement logically,
You can create static readonly property, and a static constructor and assign value from the static constructor
public class ClassName
{
static readonly int x;
static ClassName()
{
x = 10;
}
}
the compiler act as same on const property and static property, memory allocation is also same
All constants declarations are implicitly static
ref https://blogs.msdn.microsoft.com/csharpfaq/2004/03/12/why-cant-i-use-static-and-const-together/
Upvotes: 12
Reputation: 23
This is not possible using const. const should be initialized at compile time.
However, there is an alternative for this. You can use readonly which you can initialize it at runtime via constructor.
For more details, refer https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
https://www.safaribooksonline.com/library/view/c-cookbook/0596003390/ch03s25.html
Upvotes: 2
Reputation: 16277
No you cannot.
Upvotes: 1