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

Will not unboxing cause memory leaks?

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

Expand|Select|Wrap|Line Numbers
  1.  int i =3;
  2. object o = i;//Implict boxing
  3. //This object is never unboxed
  4.  
Jan 8 '09 #1
Share this Question
Share on Google+
3 Replies


10K+
P: 13,264
No. Boxing is just computationally expensive that's all.
Jan 8 '09 #2

Expert 100+
P: 190
Not memory leaks, but more memory is used when boxing value types:
Expand|Select|Wrap|Line Numbers
  1. // Value types are created on the stack.
  2. int i = 3; 
  3.  
  4. // A reference type (object) is created on the heap. 
  5. // "o" points to it.
  6. // The value copied to the heap is a copy of i, 
  7. // which is still on the stack
  8. object o = i; 
As opposed to reference types, where "boxing" is really just inheritance casting:

Expand|Select|Wrap|Line Numbers
  1. // Reference type created on the heap
  2. // "c" points to it
  3. MyClass c = new MyClass(); 
  4. // "o" is now a pointer to the same address of "c" on the heap
  5. object o = c; 
Jan 8 '09 #3

vekipeki
Expert 100+
P: 229
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.

Expand|Select|Wrap|Line Numbers
  1. int i = 1;
  2. object o = i;
  3.  
  4. // changing i will not change o
  5. i = 2;
  6.  
  7.  // this will display "1", not "2"
  8. 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.
Jan 12 '09 #4

Post your reply

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