Connecting Tech Pros Worldwide Forums | Help | Site Map

Implicit UnBoxing

Newbie
 
Join Date: Jan 2009
Posts: 9
#1: Jan 8 '09
I am a begineer in C#. I wanted to know why implicit unboxing is not allowed?

Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: Jan 8 '09

re: Implicit UnBoxing


Give an example of what you mean.
Note that in C# even primitive types extend from the Object class so you can call all the methods in the object class without needing to type cast the primitives to object class type.
Newbie
 
Join Date: Jan 2009
Posts: 9
#3: Jan 8 '09

re: Implicit UnBoxing


For Example:
Expand|Select|Wrap|Line Numbers
  1. int i= 3;
  2. object o = i;//Implicit boxing
  3. int j = o;//Implicit unboxing,does not compile.
if object o stores the type (int), why cant we perform implicit unboxing? here?
Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#4: Jan 8 '09

re: Implicit UnBoxing


Because type int is a more specific type of type object. In general you can never implicitly cast from a general type to a more specific type in strongly typed languages. Try it with any inheritance hierarchy. It has nothing to do with autoboxing.
insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#5: Jan 8 '09

re: Implicit UnBoxing


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.
Expert
 
Join Date: Sep 2008
Location: USA
Posts: 188
#6: Jan 8 '09

re: Implicit UnBoxing


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:

Expand|Select|Wrap|Line Numbers
  1. int i= 3;
  2. object o = i;//Implicit boxing
  3.  
  4. // somewhere else in your code, 
  5. // the address of object "o" is now assigned to a new string
  6. o = "oops";
  7.  
  8. // meanwhile back at the ranch...
  9. // Compiler knows o could be anything. Says, "I'm not your babysitter."
  10. int j = o; //Implicit unboxing,does not compile.
  11. int j = (int)o; // Compiles, and will blow. Your fault!
  12. string s = (string)o; // Compiles. Compiler happy. Customer happy.
  13.  
Line 11 will throw a System.InvalidCastException at runtime.
Reply