-1

This is my enumeration:

enum Stations 
{
    Central, 
    RomaStreet, 
    Milton, 
    Auchenflower, 
    Toowong, 
    Taringa, 
    Indooroopilly 
};

this is my code:

static string DepartureStation(){
    string departStationinput;
    string departStation;

    if (departStation == null){
        Console.WriteLine("Please Enter one of  the names of the stations listed above! ");
        departStationinput = Console.ReadLine(); // Gets String 
        departStation = departStationinput.ToUpper(); // Converts String into UPPER CASE
        /*Need to check if the string is matched in the ENUM and return a variable/Value for it*/

    }
    return departStation;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184

3 Answers3

2

You can use Enum.IsDefined method then parse the value:

if(Enum.IsDefined(typeof(Stations), departStationinput)
{
    var value = Enum.Parse(typeof(Stations), departStationinput);
}

Or you can use Enum.TryParse directly:

Stations enumValue;
if(Enum.TryParse(departStationinput, out enumValue))
{

}

If you want to ignore case sensitivity there is also another overload that you can use.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

First of all, about integer position, it depends on what you expect as integer position:

  • It may be the enumeration integer value.
  • The index of the enumeration value.

If you want the integer value, it's about doing this:

int value = (int)Enum.Parse(typeof(Stations), "Central"); // Substitute "Central" with a string variable

In the other hand, since enumeration values may not be always 1, 2, 3, 4..., if you're looking for the index like an 1D array:

int index = Array.IndexOf
(
     Enum.GetValues(typeof(Stations))
            .Select(value => value.ToString("f"))
            .ToArray(),
     "Central"
);
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0
var val = Enum.Parse(typeof(YourEnumType),name);
Pantelis
  • 2,060
  • 3
  • 25
  • 40
  • This answer is too short. Please explain what you mean and how it answers the question, or delete the answer. – david.pfx Apr 13 '14 at 08:56
  • Yet it answered to what the OP asked before editing his question. – Pantelis Apr 13 '14 at 09:06
  • SO depends on high quality answers that provide benefits to the general community, beyond whether they just minimally answer the question. If your answer is mostly code you should still provide an explanation of what the code does and why it answers the question. If you don't want to do that your answers will be down voted and may be deleted. – david.pfx Apr 13 '14 at 09:37