Mr.feel
Mr.feel

Reputation: 325

is it possible to assign a const variable at runtime? 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?

Upvotes: 6

Views: 13807

Answers (3)

programtreasures
programtreasures

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

svbksp
svbksp

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

David
David

Reputation: 16277

No you cannot.

  • const means that every instance of the member marked as const will be replaced with its value during compilation
  • While readonly members will be resolved at run-time.

Upvotes: 1

Related Questions