Transfer through transfer

What is the best way to list an enumeration in search of a suitable value?

string match = "A";

enum Sample { A, B, C, D }

foreach(...) {
  //should return Sample.A
}
+5
source share
4 answers

You are looking for Enum.Parse:

Sample e = (Sample)Enum.Parse(typeof(Sample), match);

You can scroll through the values ​​by calling Enum.GetValuesor Enum.GetNames.

+11
source
public Sample matchStringToSample(string match)
{
    return (Sample)Enum.Parse(typeof(Sample), match);
}

You will have to handle the case where a string match is not a valid enumeration value. Enum.Parsethrows out ArgumentExceptionin this case.

0
source
Enum.Parse(typeof(Sample), "A");
0
source

Use Enum.Parse

(Sample)Enum.Parse(typeof(Samples), "A"); //returns Sample.A
0
source

All Articles