Setting enum value at runtime in C #

Is there a way to change the enum values ​​at runtime?

for example, I have the following type

 enum MyType { TypeOne, //=5 at runtime TypeTwo //=3 at runtime } 

I want at runtime 5 to TypeOne and 3 to TypeTwo .

+6
source share
3 answers

Just consult the MSDN Help HERE

  • An enum type (also called an enum or enum) provides an efficient way to define a set of named integral constants that can be assigned to a variable.

Also HERE

In the reliable programming section. As with any constant, all references to individual enumeration values ​​are converted to numeric literals at compile time .

So, you need to rebuild your Enum idea and use it accordingly.

To answer your question - No, this is not possible.

+5
source

As others have pointed out, the answer is no.

However, you may have probably reorganized your code to use the class:

 public sealed class MyType { public int TypeOne { get; set; } public int TypeTwo { get; set; } } ... var myType = new MyType { TypeOne = 5, TypeTwo = 3 }; 

or variations of this topic.

+3
source

Recursions are compiled as static static fields, their values ​​are compiled into an assembly, so no, they cannot be changed. (Their constant values ​​can even be compiled to the places where you refer to them.)

For example, take this listing:

 enum foo { Value = 3 } 

Then you can get the field and its information as follows:

 var field = typeof(foo).GetField("Value", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); Console.WriteLine(field.GetValue(null)); Console.WriteLine(field.Attributes); 
0
source

Source: https://habr.com/ru/post/977938/


All Articles