Implicit UnBoxing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gayatri pande
    New Member
    • Jan 2009
    • 10

    Implicit UnBoxing

    I am a begineer in C#. I wanted to know why implicit unboxing is not allowed?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    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.

    Comment

    • gayatri pande
      New Member
      • Jan 2009
      • 10

      #3
      For Example:
      Code:
      int i= 3;
      object o = i;//Implicit boxing
      int j = o;//Implicit unboxing,does not compile.
      if object o stores the type (int), why cant we perform implicit unboxing? here?

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        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.

        Comment

        • Curtis Rutland
          Recognized Expert Specialist
          • Apr 2008
          • 3264

          #5
          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

          • mldisibio
            Recognized Expert New Member
            • Sep 2008
            • 191

            #6
            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:

            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.
            Line 11 will throw a System.InvalidC astException at runtime.

            Comment

            Working...