Home > Software engineering >  Get full name of the enum C#
Get full name of the enum C#

Time:01-11

Sample Code:

    public enum FruitTypeIs
    {
       Orange,
       Mango,
       Banana
    }

    public void WriteFruitType(FruitTypeIs fruitType)
    {
        string fruitTypeIs = typeof(FruitTypeIs)   "."   fruitType.ToString(); // -> FruitTypeIs.Mango
        Console.WriteLine($"{fruitTypeIs}");
    }

In the above sample code, I want to print the received enum value alongwith the enum type. For example, if I receive Mango as the value to the parameter FruitTypeIs fruitType then, I want to print the full value FruitTypeIs.Mango. Since new Fruit types could be added to the enum so, I cannot have a if/switch statement.

As a workaround I can use the statement string fruitTypeIs = typeof(FruitTypeIs) "." fruitType.ToString();, which is working fine but is there a better way to do this?

CodePudding user response:

I suggest implementing a generic method

// static - we don't need instance (this) here
// generic - T - suits for any Enum, not necessary FruitTypeIs
public static string FullEnumName<T>(T value) where T : Enum =>
  $"{typeof(T).Name}.{Enum.GetName(typeof(T), value)}";

usage:

var value = FruitTypeIs.Mango;

...

Console.Write(FullEnumName(value));

You can implement it as an extension method, e.g.

public static class EnumExtensions {
  public static string FullEnumName<T>(this T value) where T : Enum =>
    $"{value.GetType().Name}.{Enum.GetName(typeof(T), value)}";
}

and then put it

Console.Write(FruitTypeIs.Mango.FullEnumName());

CodePudding user response:

You can try extension, add an extension for Enum

public static class EnumExtension
{
    public static string GetFullType(this Enum e) => $"{e.GetType().Name}.{e}";
}

then you can use this in your code

Console.WriteLine(FruitTypeIs.Banana.GetFullType());
  • Related