MasonAlt
MasonAlt

Reputation: 369

Output an enum positions name in C#

I have an enum Planet which contains all 8 planets:

enum Planet
{
    MERCURY, VENUS, EARTH, MARS,
    JUPITER, SATURN, URANUS, NEPTUNE
}

I need to take an int position and output the corresponding enums position planet name.

So if the user entered in 2 for position, and position 2 in the enum was EARTH. It would output EARTH.

I tried using:

// Planetary Position.
Console.Write("Please enter a numeric position: ");
int position = Convert.ToInt32(Console.Read());

// Output of selected planet.
Console.Write(Enum.GetName(typeof(Planet), position));

// Prevents CMD Prompt from closing.
Console.Read();

But nothing happens when you enter in the number.

**NOTE: We have not delved into any if statements or anything like that.

Upvotes: 1

Views: 753

Answers (1)

Habib
Habib

Reputation: 223267

The way you are taking the input is wrong it should be:

int position = Convert.ToInt32(Console.ReadLine());

Console.Read reads a character and returns its ASCII value, for example for 2 you will get 50 in position, and since there is no value in your enum for 50 you get null back and thus nothing is written on the console.

(You can use int.TryParse for parsing input from console, see this answer)

You can also do:

Console.Write((Planet)position);

(and don't forget Pluto)

Upvotes: 2

Related Questions