Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to assign a const variable at runtime? c#

Tags:

c#

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?

like image 493
Mr.feel Avatar asked Dec 07 '22 15:12

Mr.feel


1 Answers

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/

like image 144
programtreasures Avatar answered Dec 19 '22 15:12

programtreasures