I am trying to get a difference between the type casting methods.
eg.
Method 1
public byte fun()
{
object value=1;
return (byte)value; // this gives me error
}
Method 2
public byte fun()
{
object value=1;
return byte.Parse(value.ToString()); // this runs
}
Method 3
public byte fun()
{
object value=1;
return Convert.ToByte(value); // this runs
}
What is the difference between all the three.
How they are working internally.
What are value type and refrence type here.
Which function can convert value type to ref type and vice versa
Edit 2
When i writes this line what datatype ‘1’ will be treated by default int32, byte or something else.
object value=1;
There are a lot of questions here.
Method 1 fails because you cannot do an unbox and a cast in a single operation. You’re setting “value” to a boxed integer. When you try to do the cast, you’re unboxing the integer and trying to cast to a byte in a single operation, which fails. This does work, btw:
Method 2 works because you’re converting the integer to a string, then using byte.Parse to convert it to a byte. This is very expensive, since it’s going to/from strings.
Method 3 works because it sees that the object in value is IConvertible (int), and uses the appropriate conversion operation to convert to byte. This is probably a more efficient way of approaching it, in this case. Since “value” is storing an int, and int supports IConvertible, Convert.ToByte will basically do a null check, then call Convert.ToByte(int), which is quite fast (it does bounds checking, and a direct cast).
I’d recommend reading Eric Lippert’s blog post titled Representation and Identity. It covers casting in detail, and explains why method 1 fails…