0

I have a generic method in my class:

public static void populateSoapBody<TEnum>(Object obj, string[] aMessage) 
   where TEnum : struct,  IComparable, IFormattable, IConvertible

then I use it to populate the class obj from the string array aMessage (as detailed here in my other question) ...

Now, for error logging, I'd like to get the name of the type argument that was passed in for the TEnum type parameter. For example:

private enum DCSSCutomerUpdate_V3
{
       ...
}

so, when I call the method like this:

Common.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage);

in that method, I want to be able to get DCSSCustomerUpdate_V3 as a string

Community
  • 1
  • 1
Our Man in Bananas
  • 5,809
  • 21
  • 91
  • 148

2 Answers2

12

I want the name of the actual constant.

obj.ToString()

gives you the name of the enumerated element if obj is a boxed instance of an enumerated type. For example:

class P
{
  enum E { ABC } 
  static void Main()
  {
     object obj = E.ABC;
     Console.WriteLine(obj.ToString()); // ABC
  }
}

I want the name of the Enumerated constant that I pass in when calling it. So, defined by TEnum so when I call the method using Common.populateSoapBody<DCSSCustomerUpdate_V3>(wsSoapBody, aMessage); I can get the string DCSSCustomerUpdate_V3

That is not a constant. You will make it much easier on both yourself and the people trying to help you if you use the right names for things.

E.ABC above is a constant. E is a type. In your example TEnum is a type parameter and the type DCSSCustomerUpdate_V3 is a type argument.

Your question is therefore:

I have a generic method M<T>(); how do I get the name of the type argument supplied for type parameter T?

The answer to that is:

void M<T>()
{
    Console.WriteLine(typeof(T).Name);
}
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • sorry Eric, I want the name of the Enumerated constant that I pass in when calling it. So, defined by `TEnum` so when I call the method using `Common.populateSoapBody(wsSoapBody, aMessage)`; I can get the string **DCSSCustomerUpdate_V3** – Our Man in Bananas Jan 27 '15 at 22:41
  • @Eric Lippert: Yes, you are right, I was blind to the fact that it's a Type .. thanks for explaining I have edited my question to give more information – Our Man in Bananas Jan 27 '15 at 22:54
  • Thank you for your explanation - I guess coming from VB6 and learning c# on the job I haven't really got a decent grounding in types yet... – Our Man in Bananas Jan 28 '15 at 09:26
5

To get the name of the type TEnum, just use:

typeof(TEnum).Name

Note that this has nothing to do with the fact that its an enum, and is not a "Enumerated constant", so I think you have some terminology wrong here as well.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117