1

I have an enum inside a class called cConstsAndEnums:

public class cConstsAndEnums
{
   public enum EnSelectedKtovet
   {
      En_KtovetMaam = 1,
      En_KtovetTmg
   };
}

In other class I have switch:

switch (dr["rowSelectedKtovet"].ToString())
{
    case cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam:
       doSomthing;
       break;
    default:
}

The problem is that I'm getting an error: Cannot implicitly convert type 'cConstsAndEnums.EnSelectedKtovet' to 'string'.

I try to do:

case (string)cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam:

but I have error: Cannot convert type 'cConstsAndEnums.EnSelectedKtovet' to 'string'.

Tried also:

   case Convert.ToString(cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam):

but again I have error: A constant value is expected.

Please help.

Thanks.

shlomi
  • 523
  • 3
  • 13
  • 26
  • 1
    Of what type is `dr["rowSelectedKtovet"]`? – adjan Jun 15 '17 at 07:50
  • 1
    Possible duplicate of [Convert Enum to String](https://stackoverflow.com/questions/483794/convert-enum-to-string) – Chawin Jun 15 '17 at 07:53
  • @adjan, it a datarow type but this is ok, don't have error on it. – shlomi Jun 15 '17 at 07:57
  • @Chawin, I saw it but it does not help me. – shlomi Jun 15 '17 at 07:58
  • @shlomi why doesn't it help? It's actually the correct answer - in fact, this question should be closed as a duplicate.. If you want to get the string representation of an enum value, use `Enum.GetName` – Panagiotis Kanavos Jun 15 '17 at 08:01
  • @shlomi I'll also repeast, what is the type of `dr["rowSelectedKtovet"]`? It's definitely *NOT* a datarow. It's a string or integer wrapped as an object. You *DON'T* need to convert it to a string at all to compare it against another value. If it's an int, just compare the values directly - enums are integers after all.If it's a string, parse it to an enum. *DON'T* convert it to a string without reason – Panagiotis Kanavos Jun 15 '17 at 08:05
  • @PanagiotisKanavos I'm sorry, you are right, it's a string type. But when I try to parse it to enum I have an error that cannot implictly convert type object to cConstsAndEnums.EnSelectedKtovet. An explicit conversion exists. – shlomi Jun 15 '17 at 08:17
  • Parsing doesn't return any conversion errors. Post the string value and your actual code. `Enum.Parse(typeof(cConstsAndEnums.EnSelectedKtovet),"En_KtovetMaam")` works just fine – Panagiotis Kanavos Jun 15 '17 at 08:21

6 Answers6

3

The reason is the data type of the switch (string) is different to your cases (enum values). Trying to solve this by using .ToString() means you are doing an operation, but a case needs always a constant value. Do it the other way and cast the string to the enum before using it at the switch.

cConstsAndEnums.EnSelectedKtovet enumValue = (cConstsAndEnums.EnSelectedKtovet)
    Enum.Parse(typeof(cConstsAndEnums.EnSelectedKtovet, dr["rowSelectedKtovet"].ToString());
switch (enumValue)
{
    case cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam:
    ...
}

Also think about to store the numeric value of the enumeration instead of the string value. Every enum literal has a value which you can simply cast to an integer:

EnSelectedKtovet enumValue = EnSelectedKtovet.En_KtovetMaam;
int storedEnumValue = (int)enumValue;
EnSelectedKtovet restoredEnumValue = (EnSelectedKtovet)storedEnumValue;

With this solution you dont need to deal with any string, which is much more safe and comfortable.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • Maybe I wasn't clear enougth, The errors are on case, not on the switch – shlomi Jun 15 '17 at 08:01
  • @shlomi the error is that you use `ToString()` at all. You don't need it. What is the field's type? Number or string? Why use `ToString()` when you want to compare it agains a numeric value like an enum anyway? – Panagiotis Kanavos Jun 15 '17 at 08:06
  • @Fruchtzwerg Thanks but I get an error: cannot implictly convert type object to cConstsAndEnums.EnSelectedKtovet. An explicit conversion exists. – shlomi Jun 15 '17 at 08:19
  • Correct - I forgot to cast the result of Enum.Parse ... I've updated the answer. Should do the trick now. – Fruchtzwerg Jun 15 '17 at 08:23
  • Thank you All!!! the cast to the resault was missing. work perfect. – shlomi Jun 15 '17 at 08:44
0

You should use Enum.Parse() method (in case if you ensure that string has always prvoded enum value) or Enum.TryParse() (in case if string cuold have anything, so you can set your enum to default value)

In your case try this:

var myEnum = (EnSelectedKtovet)Enum.Parse(typeof(EnSelectedKtovet), dr["rowSelectedKtovet"].ToString());

switch (myEnum)
{
 case EnSelectedKtovet.En_KtovetMaam:
       doSomthing;
        break;
       default:
}
DolceVita
  • 2,090
  • 1
  • 23
  • 35
0

In your switch statement, convert it to the enum

switch(Enum.Parse(typeof(EnSelectedKtovet), dr["rowSelectedKtovet"].ToString()){
  case cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam:
     doSomthing;
     break;
  default:
}
David Lindon
  • 305
  • 2
  • 8
0
switch ((EnSelectedKtovet)int.Parse(dr["rowSelectedKtovet"].ToString()))
{
    case EnSelectedKtovet.En_KtovetMaam:

        break;

    default:

        break;
}

I hope it will work for you.

Tien Nguyen Ngoc
  • 1,555
  • 1
  • 8
  • 17
0

This is a case of the XY Problem. You are asking about your attempted solution, not the actual problem.

In this case the actual problem is that you read an enum value from the database. The index method returns an object so you can't compare it with anything else directly. You'd have to cast it to an int (if the database returns an int) or a string. You can cast it to an enum directly too, since enums are basically named integers.

Instead of that, you tried to convert it to a string. When you tried to compare that string to the enum values, you got a compilation error because obviously an enum isn't a string.

If the underlying field value is an integer, you can just cast it to the enum's type:

var value=(cConstsAndEnums.EnSelectedKtovet)dr["rowSelectedKtovet"];
switch (value)
{
    case cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam:
       doSomthing;
       break;
    default:
}

If it's a string that contains the enum name, you'll have to parse the string with Enum.Parse or Enum.TryParse

var fieldValue=(string)dr["rowSelectedKtovet"];
var value=Enum.Parse(typeof(cConstsAndEnums.EnSelectedKtovet),fieldValue);
switch (value)
...

With a bit of C# 7 and pattern matching magic, you could match both cases:

var value=dr["rowSelectedKtovet"];
switch(value)
{
    case int val when Enum.IsDefined(typeof(cConstsAndEnums.EnSelectedKtovet),val) :
        var enumValue=(cConstsAndEnums.EnSelectedKtovet)val;
        //Use enumValue 
        break;
    case string s when Enum.TryParse<cConstsAndEnums.EnSelectedKtovet>(s,out var enumValue):
        //Use enumValue 
        break;
    default :
        throw new ArgumentException($"Unknown {value}");
}
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • I did what you suggest but now I get error on switch(value): A switch expression or case label must be a bool,char,string,enum or corresponding nullable type – shlomi Jun 15 '17 at 08:25
  • And it is. All snippets use an actual Enum. Only the pattern matching is different, but also compiles with C# 7. What did you *actually* try? What is the *actual* value returned by the database? – Panagiotis Kanavos Jun 15 '17 at 08:29
-1

You Can try.ToString("D") to compare with Enum value.

  string selectedValue= dr["rowSelectedKtovet"].ToString();
    if(selectedValue==cConstsAndEnums.EnSelectedKtovet.En_KtovetMaam.ToString("D"))
      {
        doSomthing();
      }
alnaji
  • 473
  • 3
  • 9
  • Better yet, don't conver to string at all. What you typed would only work if `dr["rowSelectedKtovet"]` was already an integer or enum value – Panagiotis Kanavos Jun 15 '17 at 08:29