17

Is there any way that I can change enum values at run-time?

e.g I have following type

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

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

3
  • 1
    This isn't possible. Commented Nov 9, 2014 at 11:03
  • 3
    Why would you even want this? Commented Nov 9, 2014 at 11:04
  • 15
    +1 I don't understand the down-voters. Don't down-vote the question because the answer is 'no' up-vote the answer that is 'no' instead. Commented Dec 14, 2015 at 22:52

3 Answers 3

11

As others have pointed out, the answer is no.

You could however probably refactor your code to use a class instead:

public sealed class MyType
{
   public int TypeOne { get; set; }
   public int TypeTwo { get; set; }
}

...

var myType = new MyType { TypeOne  = 5, TypeTwo = 3 };

or variations on that theme.

Sign up to request clarification or add additional context in comments.

Comments

8

Just refer to MSDN help HERE

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

Also HERE

In the Robust Programming Section - Just as with any constant, all references to the individual values of an enum are converted to numeric literals at compile time.

So you need to realign your idea of Enum and use it accordingly.

To answer your question - No it is not possible.

Comments

0

Enums are compiled as constant static fields, their values are compiled into you assembly, so no, it's not possible to change them. (Their constant values may even be compiled into places where you reference them.)

Eg take this enum:

enum foo
{
    Value = 3
}

Then you can get the field and its information like this:

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

2 Comments

Incorrect, they are compiled as constants, not static fields.
@DavidG I added sample code. They work exactly like fields. Constants are implemented as fields as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.