0

I have an enum definition like this:

public enum columnName
{
  Name
  Age
  DOB
}

I would like to create a class with properties' names equals to enum values; i.e.:

public class Person
{
  public string Name {get;set;}
  public string Age {get;set;}
  public string DOB {get;set;}
}

Instead of having static properties' names like in the class above, is there any possibility to refer to them via the enum values? I'm talking about something like:

public class Person
{
  public string columnName.Name.toString() {get;set;}
  public string columnName.Age.toString() {get;set;}
  public string columnName.DOB.toString() {get;set;}
}
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • Does this answer your question? [How do I name variables dynamically in C#?](https://stackoverflow.com/questions/5033675/how-do-i-name-variables-dynamically-in-c) and [Create dynamic variable name](https://stackoverflow.com/questions/20857773/create-dynamic-variable-name) and [How to create variables with dynamic names in C#?](https://stackoverflow.com/questions/1147967/how-to-create-variables-with-dynamic-names-in-c) and [Creating dynamic variable names in C#](https://stackoverflow.com/questions/11891381/creating-dynamic-variable-names-in-c-sharp) –  Aug 02 '21 at 14:42
  • Need to use Reflecton. See : https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties?force_isolation=true&view=net-5.0 – jdweng Aug 02 '21 at 14:44
  • No, it is not possible to create variables in the source code at runtime. But you can use a dictionary: so you can inject names using [Enum.GetNames](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames). Or you can use a handmade source code generator which takes the file having the enum and creates another file for the class, in case of multiple enumerations... But why do you want string properties matching enum's names? What is the goal and usage? –  Aug 02 '21 at 14:47
  • This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why do you want a class to have properties associated with enum values? Would using a dictionary work instead of a class? – Joe Sewell Aug 02 '21 at 14:55

1 Answers1

-1

I don't know any possible way to obtain what you want with a class. But if you want, you could obtain the desired result with an anonymous type. You should write something like this:

var AField = MyEnum.A.ToString();
var anon = new { AField = "AAA" };

You can see an example here:

https://dotnetfiddle.net/Zh6NmJ

ufo
  • 674
  • 2
  • 12
  • 35