0

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
        }

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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);

1 Comment

Yeah he should really drop the "e" prefix
1

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;

1 Comment

Can you help explain why this is the default and using the enum value is not the default?
0

I guess you mean this

eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)

1 Comment

The ToString is redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.