Reputation: 23295
What C# code would output the following for a variable of the enum type below?
Dentist (2533)
public enum eOccupationCode
{
Butcher = 2531,
Baker = 2532,
Dentist = 2533,
Podiatrist = 2534,
Surgeon = 2535,
Other = 2539
}
Upvotes: 0
Views: 3425
Reputation: 11626
You can also use the format strings g
, G
, f
, F
to print the name of the enumeration entry, or d
and D
to print the decimal representation:
var dentist = eOccupationCode.Dentist;
Console.WriteLine(dentist.ToString("G")); // Prints: "Dentist"
Console.WriteLine(dentist.ToString("D")); // Prints: "2533"
... or as handy one-liner:
Console.WriteLine("{0:G} ({0:D})", dentist); // Prints: "Dentist (2533)"
This works with Console.WriteLine
, just as with String.Format
.
Upvotes: 9
Reputation: 38220
I guess you mean this
eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)
Upvotes: 0
Reputation: 14618
What C# code would output the following for a variable of the enum type below?
Without casting, it would output the enum identifier: Dentist
If you need to access that enum value you need to cast it:
int value = (int)eOccupationCode.Dentist;
Upvotes: 1
Reputation: 1502206
It sounds like you want something like:
// Please drop the "e" prefix...
OccupationCode code = OccupationCode.Dentist;
string text = string.Format("{0} ({1})", code, (int) code);
Upvotes: 7