Will not unboxing cause memory leaks?

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

    Will not unboxing cause memory leaks?

    Is memory leaks possible if a value type is boxed and is not unboxed?

    Code:
     int i =3;
    object o = i;//Implict boxing
    //This object is never unboxed
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    No. Boxing is just computationally expensive that's all.

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      Not memory leaks, but more memory is used when boxing value types:
      Code:
      // Value types are created on the stack.
      int i = 3; 
      
      // A reference type (object) is created on the heap. 
      // "o" points to it.
      // The value copied to the heap is a copy of i, 
      // which is still on the stack
      object o = i;
      As opposed to reference types, where "boxing" is really just inheritance casting:

      Code:
      // Reference type created on the heap
      // "c" points to it
      MyClass c = new MyClass(); 
      // "o" is now a pointer to the same address of "c" on the heap
      object o = c;

      Comment

      • vekipeki
        Recognized Expert New Member
        • Nov 2007
        • 229

        #4
        When you say "This object is never unboxed", note that "boxing" a value type does not do anything to the original type, just like "unboxing" does not change the original reference type.

        The name "boxing" is a bit confusing because it sounds like you are encapsulating your original value in some way, but you are actually creating a new object which has the initial value same as your original value.

        Code:
        int i = 1;
        object o = i;
        
        // changing i will not change o
        i = 2;
        
         // this will display "1", not "2"
        Console.WriteLine(o);
        Since your new object is a reference type, GC will collect it when it gets out scope, just as any other object, so there will not be any memory leaks.

        Comment

        Working...