Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial enum compiled in runtime - alternative

Tags:

c#

roslyn

I would like to do something like a partial enum. If I know C# has no support for this. My idea is to do Dictionary<PartialEnum, MyClass> in MyClass2. Dictionary contains some properties loaded from file and I want to have a possibility to add some other "properties" (members of PartialEnum). I am using the Roslyn so I can compile some "second" part of enum during runtime but don't know how to do it. (partial static class is also not supported so I cannot use public readonly members)

MyClass{
  string value;

  public string Value{
     get{ return value;}
  }
}

MyClass2{

  private Dictionary<PartialEnum,MyClass> properties;

}

I can use string like key but it is not very nice. So is it possible to do something like:

partial enum PartialEnum{
 Name,
 Group, ...
}

and runtime compiled part

partial enum PartialEnum{     
 runTimeLasName,
 runTimeTitle, ...
}
like image 590
wolen Avatar asked Nov 03 '22 23:11

wolen


1 Answers

It seems to me that you don't actually need an enum here. You want to add some values to it at runtime, which means enum doesn't fit your needs. But you can create a class that does. Something like:

class PartialEnum
{
    private static readonly Dictionary<string, PartialEnum> Values =
        new Dictionary<string, PartialEnum>();

    public string Id { get; private set; }

    private PartialEnum(string id)
    {
        Id = id;
    }

    public static PartialEnum GetValue(string id)
    {
        PartialEnum value;
        if (!Values.TryGetValue(id, out value))
        {
            value = new PartialEnum(id);
        }

        return value;
    }

    public static PartialEnum Name { get { return GetValue("Name"); } }

    public static PartialEnum Group { get { return GetValue("Group"); } }
}

If you want to use one of the predefined values, access the static property (e.g. PartialEnum.Name). If you want to use a runtime-defined value, use the GetValue() method (e.g. PartialEnum.GetValue("runTimeLastName")).

like image 175
svick Avatar answered Nov 12 '22 16:11

svick