Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bool to byte

Tags:

c#

bool myBool = true;
byte myByte;
  • This conversion runs myByte = Convert.ToByte(myBool);
  • This conversion does not run myByte = (byte)myBool;

For a newbie(me): why are the above different?

like image 664
whytheq Avatar asked Jan 16 '23 09:01

whytheq


1 Answers

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.

like image 108
Jon Skeet Avatar answered Jan 31 '23 02:01

Jon Skeet