Well here is my shot at it:
Method 1
This is a type cast, i.e. the value has to be of a type that can be implcitly or explicitly converted into a byte. Furthermore, value must not be outside the bounds of a byte.
The call fails as the compiler does not have any information what type of object it should cast from, and thus cannot perform a implicit or explicit conversion. Doing
int obj = 1;
byte b = (byte) obj;
or
byte b = (byte) (int) obj;
works. The second option uses expicit unboxing (thus providing the needed information) as described in Reed Copsey's comment and post. The link provided by Reed Copsey's comment explains this in detail.
For custom objects casts use the implicit and explicit conversions are operators which are static methods defined on the class. For object
no implicit or explicit operations exist (see link forthe reason why), while for int
these operations exist.
Method 2
Here you are parsing a string the value of the string has to be a number that is inside the bound of a byte. Here you could also use TryParse
which allows you to check whether the conversion will succeed.
Method 3
Uses type conversion of the Convert
class. This is the most flexible method that supports most of the common types. Here, the value must be convertible to a numer, and the value must be inside the bounds of the byte. The Convert
class uses IConvertible
to convert between the different types and, therefore, is extensible.