views:

289

answers:

3

Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do:

enum Rank { A, B, C }

Rank myRank = Rank.A;
string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string'
string myString2 = Rank.A.ToString(); // OK: but is extra work
+5  A: 

No. An enum is it's own type, if you want to convert it to something else, you have to do some work.

However, depending on what you're doing with it, some tasks will call ToString() on it automatically for you. For example, you can do:

Console.Writeline(Rank.A);
womp
Ok, just wishful thinking on my part.
dcompiled
Also, just to be clear, there's nothing special about `Console.WriteLine`, it just has an overload that takes an Object and the enum is getting boxed, passed as an object and then `WriteLine` calls `ToString` on it.
Dean Harding
@dcompiled - if you're curious, it is possible to write your own implicit conversion operator for your enum to a string! http://www.csharphelp.com/2006/10/type-conversion-and-conversion-operators-in-c/
Mike Atlas
+1  A: 

No, but at least you can do things with enums that will call their ToString() methods when you might need to use their string value, e.g.:

Console.WriteLine(Rank.A); //prints "A".
Mike Atlas
A: 

The correct syntax should be

myRank.ToString("F");
Syd