bool myBool = true;
byte myByte;
myByte = Convert.ToByte(myBool);
myByte = (byte)myBool;
For a newbie(me
): why are the above different?
Convert.ToByte
is a method - it can do whatever it wants to, probably along the lines of:
return input ? (byte) 1 : (byte) 0;
A cast is a language-level operation. It requires that either the language knows about the conversion itself, or that one of the types involved has a user-defined conversion with the right input and output types. Neither of these is the case when converting from bool
to byte
.
Basically, the language doesn't define what that cast should mean, so the compiler prohibits it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With