int number = 9;
object obj = number;
As you can see, conversion is implicit. Well, of course, if you want you can do it explicitly:
int number = 9;
object obj = (object)number;
Unboxing is not as as safe as boxing, that's why you have to do it explicitly:
int number = 9;
object obj = number;
int numberOuttaBox = (int)obj;
Oh, and remember to extract exactly what you previously boxed, because for some reason C# is like real strict about it. Basically what I mean is that you cannot get away with this:
int number = 9;
object obj = number;
float numberOuttaBox = (float)obj;
Such misbehaving is gonna result in getting the following exception:
System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.Single'.'
In general, its very easy to bypass it, just unbox what you previously put and then cast to whatever you want either implicitly:
int number = 9;
object obj = number;
float numberOuttaBox = (int)obj;
Or explicitly:
int number = 9;
object obj = number;
float numberOuttaBox = (float)(int)obj; // Excessive, but it's just an example.
Please keep in mind that boxing/unboxing is not casting and excessive use of this operation may severely affect overall performance.
object obj = number;
float numberOuttaBox = (int)obj;
Or explicitly:
int number = 9;
object obj = number;
float numberOuttaBox = (float)(int)obj; // Excessive, but it's just an example.
Please keep in mind that boxing/unboxing is not casting and excessive use of this operation may severely affect overall performance.
No comments:
Post a Comment