-2

I need to assign a string to a Enum value. My scenario and code below

Am accessing a webservice method say addWhere(int i ,int j,Comparison)

Where Comparison is of type Enum.

Am fetching value from UI and having it in a string

string strComparison= "AND"; or

string strComparison= "OR"

i need to set these values to ENUM. I tried the below code

addWhere(2 ,3,Enum.Parse(typeof(Comparison),strComparison))

But didnt worked. What is the way to solve this or any alternate methods ?

Thanks

user2067567
  • 3,695
  • 15
  • 49
  • 77
  • `Enum.Parse` is the solution, there is no good alternative. You don't say what goes wrong. See the duplicate or the documentation. – Jodrell Apr 16 '13 at 10:47
  • 1
    "didn't work" is never an acceptable problem description. **What** didn't work? What **error** did you get? Please keep in mind to include all **relevant details** in your questions. – J. Steen Apr 16 '13 at 10:48

4 Answers4

2

Looks like your missing the return cast i.e.

(Comparison)Enum.Parse(typeof(Comparison), strComparison);

Enum.Parse returns an object were as your addWhere method is expecting a Comparison type value.

James
  • 80,725
  • 18
  • 167
  • 237
0

You must cast the result of Enum.Parse to the correct type:

addWhere(2, 3, (Comparison)Enum.Parse(typeof(Comparison), strComparison));
John Willemse
  • 6,608
  • 7
  • 31
  • 45
0

You can do something like:

Comparison comparison;
if(Comparison.TryParse(strComparison, out comparison))
{
   // Work with the converted Comparison
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95
0

As said in earlier posts, you might be missing type casting.

enum Comparision
{
        AND,
        OR
}

class Program
{
    static void Main(string[] args)
    {
        Comparision cmp = (Comparision)Enum.Parse(typeof (Comparision), "And", true);
        Console.WriteLine(cmp == Comparision.OR  );
        Console.WriteLine(cmp == Comparision.AND);
    }
}