C# Convert an enum to other type of enum

Sometimes, if we want to do convert between two enums, firstly, we may think about one way:

var myGender = (MyGender)(int)TheirGender.TheirMale;

 

Obviously, it's dangerous, if the int value of TheirMale in TheirGender doesn't match corresponding MyGender, it will fail to convert.

So, the solution may be to use switch case, one elegent method is to written as extensions.

We can simply use like  theirGender.ToMyGender()  to invoke.

Here is the solution:

 

public static class TheirGenderExtensions
{
    public static MyGender ToMyGender(this TheirGender value)
    {
        // insert switch statement here
    }
}

public static class MyGenderExtensions
{
    public static TheirGender ToTheirGender(this MyGender value)
    {
        // insert switch statement here
    }
}

  

ref: http://stackoverflow.com/questions/1818131/convert-an-enum-to-another-type-of-enum

posted @ 2016-03-21 15:28  Jeremy Wu  阅读(249)  评论(0编辑  收藏  举报