inside
inside

Reputation: 3177

Get Assembly qualified name of enum member

I have enum

  namespace ConsoleTestApplication
  {
    public enum Cars
    {
        Audi,
        BMW,
        Ford
    }
  }

now I want to get fully qualified name of enum member

so the result will be

ConsoleTestApplication.Cars.Audi

something like

Cars.Audi.GetType().FullName;

or

Cars.Audi.GetType().AssemblyQualifiedName;

what I am looking for, but non of those actually does what I need.

The reason of why I need it, because I have two identical enums in different namespaces (don't blame me on bad design, this is how it should be in my project) and in one part of my program I need to use member of this enum, but because I have same enums it's gonna complain on ambiguity between same enums in different namespaces. So in order to avoid it I have to provide fully qualified name, reason of why I can't do it manually because this is kind of auto generated files, so I need to specify it programmaticaly at compile time

Upvotes: 0

Views: 1760

Answers (2)

Ben Reich
Ben Reich

Reputation: 16324

Do you just need a string? If so, you could just use an extension method like this:

public static string GetFullyQualifiedEnumName<T>(this T @this) where T : struct, IConvertible
{
    if (!typeof(T).IsEnum) 
    {
        throw new ArgumentException("T must be an enum");
    }
    var type = typeof(T);
    return string.Format("{0}.{1}.{2}", type.Namespace, type.Name, Enum.GetName(type, @this));      
}

If you're just trying to reference an ambiguous enum, just use MyNameSpace.MyEnum.MyValue, which would disambiguate it from MyOtherNameSpace.MyEnum.MyValue.

Upvotes: 2

itsme86
itsme86

Reputation: 19496

You could fake it with a concatenated result:

class Program
{
    static void Main(string[] args)
    {
        Cars car = Cars.Audi;

        Console.WriteLine("{0}.{1}", car.GetType().FullName, Enum.GetName(typeof(Cars), car));
    }
}

enum Cars { Audi, BMW, Ford }

Upvotes: 0

Related Questions