By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,991 Members | 1,917 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,991 IT Pros & Developers. It's quick & easy.

Implicit UnBoxing

P: 10
I am a begineer in C#. I wanted to know why implicit unboxing is not allowed?
Jan 8 '09 #1
Share this Question
Share on Google+
5 Replies


10K+
P: 13,264
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.
Jan 8 '09 #2

P: 10
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?
Jan 8 '09 #3

10K+
P: 13,264
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.
Jan 8 '09 #4

Curtis Rutland
Expert 2.5K+
P: 3,256
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.
Jan 8 '09 #5

Expert 100+
P: 190
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.
Jan 8 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.