Enum ToString with user friendly strings

后端 未结 23 2058
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 11:44

My enum consists of the following values:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

I want to be able to

23条回答
  •  一整个雨季
    2020-11-22 12:38

    The simplest way is just to include this extension class into your project, it will work with any enum in the project:

    public static class EnumExtensions
    {
        public static string ToFriendlyString(this Enum code)
        {
            return Enum.GetName(code.GetType(), code);
        }
    }
    

    Usage:

    enum ExampleEnum
    {
        Demo = 0,
        Test = 1, 
        Live = 2
    }
    

    ...

    ExampleEnum ee = ExampleEnum.Live;
    Console.WriteLine(ee.ToFriendlyString());
    

提交回复
热议问题