c# - Unable to implicitly convert value from enum even though the underlying type is specified -


in following code sample define enum , specify underlying type byte. attempt assign byte value , switch on enum's values error: cannot implicitly convert type 'cmdlnflags' 'byte'. explicit conversion exists (are missing 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();     } } 

it's easy enough fix, cast byte, why have cast if underlying type specified enum? what's point of specifying underlying type if have cast anyway?

if cast, works. example:

        byte switchbyte = (byte)cmdlnflags.valb;         switch (switchbyte) {             case (byte)cmdlnflags.vala: console.writeline('a'); break;             case (byte)cmdlnflags.valb: console.writeline('b'); break;         } 

you have cast make sure that's mean do. it's type safety feature.

you should think of enum being distinct type underlying type - , other enums same underlying type. they're sufficiently different if want use 1 another, need cast.

it can pain, it's thing.

why casting before switch anyway though? switch on actual enum values:

cmdlnflags switchflag = cmdlnflags.valb; switch (switchflag) {     case cmdlnflags.vala: console.writeline('a'); break;     case cmdlnflags.valb: console.writeline('b'); break; } 

here, don't really want treat flag byte - want treat flag , switch on it. that's should do.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -