0

Is it possible, in C# .NET, to convert a list of string into an enum of values.

Let's imagine I get the list of string from somewhere (API call for example) and I want to convert it to an enum like that :

List<string> MyList = MyService.GetList();
//MyList = {"Red", "Blue", "Yellow"}


//Here the code to create my enum from MyList

//... Somewhere else in the code
var colorRed = MyEnum.RED;
var colorBlue = MyEnum.BLUE;

Is it possible here to create the MyEnum enum, which doesn't exists yet, and if yes, how ? If it's not, what workaround could I use?

I have tried to use the list only, but I need an enum in order to use it like that

MyEnum.RED;
bschaffh
  • 114
  • 8
  • I think he wants to create somehow a dynamic Enum based on the list items... but I don't see the point if you don't know the items how can u know what to use... – D A Jun 23 '23 at 13:52
  • I don't think the duplicate is asking the same question; AFAICT, this question is asking about dynamic code generation during runtime, not simply parsing a string to an already-known enum... – Heretic Monkey Jun 23 '23 at 13:54
  • Thanks for reading my post. Yes actually i think it's not the same question as mentionned. At the moment i have a hard-coded enum, and I want it to become dynamic according to the list i get from the service – bschaffh Jun 23 '23 at 13:57
  • Enums are basically like constants; substitutes for values. So when you write `var colorRed = MyEnum.RED`, the compiler makes `colorRed` the string `"Red"`. Having "dynamic constants" doesn't make much sense. – Heretic Monkey Jun 23 '23 at 14:00
  • 1
    This is not possible. Enums are a compile-time item. That is, the definitions MUST be available to the compiler, before any code actually runs. But list data is not filled until run-time, after the fully-compiled program begins to execute. There are things you can do to emit IL on the fly, but this is still at run time and won't help you writing code to use the enum. – Joel Coehoorn Jun 23 '23 at 14:03
  • I see, thank you for your answers, i will try using the list and not enum then. – bschaffh Jun 23 '23 at 14:04
  • Even if that would be possible, how would you use them? eg. if you were to use `MyEnum.Yellow` in your code, why should that enum be generated in the first place? – Rand Random Jun 23 '23 at 14:04

0 Answers0