Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attributes to cut down on enum to enum mapping and enum/const to action switch statments

I imagine everyone has seen code like:

public void Server2ClientEnumConvert( ServerEnum server)
{
    switch(server)
    {
       case ServerEnum.One:
           return ClientEnum.ABC
       //And so on.

Instead of this badness we could do somthing like:

public enum ServerEnum
{
     [Enum2Enum(ClientEnum.ABC)]
     One,
}

Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.

The problem I am having here is in the declaration of the Enum2Enum attribute.

This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.

public class EnumToEnumAttribute : Attribute
{
    public EnumToEnumAttribute(object o){}
}

This fails to compile.

public class EnumToEnumAttribute : Attribute
{
    public EnumToEnumAttribute(Enum e){}
}

Is there a reason for the compile error? How else could I pass in the information needed to map besides:

EnumtoEnumAttribute(Type dest, string enumString)

This seems too verbose but if it is the only way then I guess I will use it.

like image 860
Ben McNiel Avatar asked Sep 02 '08 17:09

Ben McNiel


1 Answers

Using almost the same example, you can achieve this directly in the enum:

public enum ServerEnum
{
   One = ClientEnum.ABC,
}

This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead.

like image 165
Scott Dorman Avatar answered Oct 18 '22 20:10

Scott Dorman