0

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

inside
  • 3,047
  • 10
  • 49
  • 75
  • How will you be using it once you have it? Why find it in reverse? Where will you ever have `Cars.Audi` that you don't also have `ConsoleTestApplication.Cars.Audi`? – DonBoitnott Jun 04 '13 at 15:49
  • @Stanislav I still don't understand what you want. Do you want a string, type, object, or what? You've been given a couple of ways to get the FQN already, so it must be something besides a string, but I can't tell what it is from your question. Please don't use the word "name" to describe what you're looking for. That says "string" to me. Explain what type you're looking for. – itsme86 Jun 04 '13 at 16:30

2 Answers2

2

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.

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
0

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 }
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • yeah, I could, but I need this value not to print it but to use it. because I have two same enums in different namespaces and in order to not have ambiguity I need to provide fully qualified name – inside Jun 04 '13 at 15:43
  • I don't understand. Can you update your question with an example of how you will be using the full name? – Ben Reich Jun 04 '13 at 15:48