It is not possible to implicitly convert a value from an enumeration, even if a base type is specified

In the following code example, I define an enumeration and specify its base type as a byte. Then I try to assign a byte value and include the enumeration values, but I get the error message: Cannot implicitly convert type 'CmdlnFlags' to 'byte'. An explicit conversion exists (are you missing a cast?) Cannot implicitly convert type 'CmdlnFlags' to 'byte'. An explicit conversion exists (are you missing a cast?)

The code:

 using System; public enum CmdlnFlags: byte { ValA = (byte)'a', ValB = (byte)'b', } public class Sample { public static void Main() { byte switchByte = CmdlnFlags.ValB; switch (switchByte) { case CmdlnFlags.ValA: Console.WriteLine('A'); break; case CmdlnFlags.ValB: Console.WriteLine('B'); break; } Console.ReadKey(); } } 

Easy enough to fix, just pass in bytes, but why do I need to discard if the base type is specified for enumeration? What is the point of specifying the base type if you still need to cast?

If I give up, everything will work. Example:

  byte switchByte = (byte)CmdlnFlags.ValB; switch (switchByte) { case (byte)CmdlnFlags.ValA: Console.WriteLine('A'); break; case (byte)CmdlnFlags.ValB: Console.WriteLine('B'); break; } 
+6
source share
2 answers

You have to quit to make sure that what you want to do is really. This is a type safety feature.

You should think that an enumeration is a separate type from its base type - and from other enumerations with the same base type. They are quite different, that if you want to use them as one, you need to quit.

Sometimes it can be a pain, but ultimately it's good.

Why are you still casting in front of the switch? Just include the actual enumeration values:

 CmdlnFlags switchFlag = CmdlnFlags.ValB; switch (switchFlag) { case CmdlnFlags.ValA: Console.WriteLine('A'); break; case CmdlnFlags.ValB: Console.WriteLine('B'); break; } 

Here you do not want to treat the flag as a byte - you want to treat it as a flag and enable it. So what exactly should you do.

+5
source

In most cases, such drops are not needed. Instead of using a variable of type byte to control the switch, simply create a variable of type CmdlnFlags .

  CmdlnFlags switchValue = CmdlnFlags.ValB; switch (switchValue) { case CmdlnFlags.ValA: Console.WriteLine('A'); break; case CmdlnFlags.ValB: Console.WriteLine('B'); break; } 

Ghosts should encourage proper program design. Usually you do not want to use an enumeration as a numeric value.

+2
source

Source: https://habr.com/ru/post/885672/


All Articles