Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# enum to string auto-conversion?

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
like image 711
dcompiled Avatar asked Jun 09 '10 23:06

dcompiled


1 Answers

No. An enum is its own type, so 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 methods will call ToString() on it automatically for you. For example, you can do:

Console.Writeline(Rank.A);
like image 56
womp Avatar answered Oct 14 '22 19:10

womp