object Boxing

  • Thread starter Thread starter Maheal
  • Start date Start date
M

Maheal

Take the following code:

string s = "Hello";
object a = s;
object b = s;


would (a == b) return a true value? Basically, I want to know if
boxing the same value references only one object, or if each object
creates a new reference, but with the same value. Thanks!
 
Hi Maheal,

With such a small question, it's actually quicker to start a project and put that code
in it and see what happens.

When you do, don't forget that strings are reference types. You'll have to
do the same with a couple of ints and a structure to convince yourself that the
behaviour is consistent across the board.

Then you can come back and say - I found 'xxx' can someone explain. But
you might not need to do that because your experiment may have told you
enough.

Regards,
Fergus
 
Maheal said:
Take the following code:

string s = "Hello";
object a = s;
object b = s;


would (a == b) return a true value? Basically, I want to know if
boxing the same value references only one object, or if each object
creates a new reference, but with the same value. Thanks!

There's no boxing going on there - string is a reference type.

However, if you do:

int i = 10;
object a = i;
object b = i;

then the objects will indeed be different, and (a==b) is false.
 
Back
Top