I am a begineer in C#. I wanted to know why implicit unboxing is not allowed?
Implicit UnBoxing
Collapse
X
-
Tags: None
-
For Example:
if object o stores the type (int), why cant we perform implicit unboxing? here?Code:int i= 3; object o = i;//Implicit boxing int j = o;//Implicit unboxing,does not compile.
Comment
-
Explicit casting is just part of the language. It's safe, because it guarantees that you will only be putting something that fits in the box in it.
Effectively what this means is that with C#, you have to tell it exactly what you want it to do. It won't try to automatically cast your objects for you. It means you have greater control over your programming, but you also have to remember to manually do a few things.
Explicit casting also builds good habits, and makes for much more readable code.Comment
-
The compiler intentionally insures that the object's type can be guaranteed, and if not, then your are responsible for the application blowing-up, not the compiler.
It is trying to protect against the following:
Line 11 will throw a System.InvalidC astException at runtime.Code:int i= 3; object o = i;//Implicit boxing // somewhere else in your code, // the address of object "o" is now assigned to a new string o = "oops"; // meanwhile back at the ranch... // Compiler knows o could be anything. Says, "I'm not your babysitter." int j = o; //Implicit unboxing,does not compile. int j = (int)o; // Compiles, and will blow. Your fault! string s = (string)o; // Compiles. Compiler happy. Customer happy.
Comment
Comment