implicit autoboxing

  • Thread starter Thread starter cody
  • Start date Start date
C

cody

hi!

i always hear about the dangers (performance loss) that comes with implicit
autoboxing. when are situations where this happens?

i only know this happens when i assign a value type to a variable of type
object.

int i = 1234;
object obj = i; // here the implicit conversion takes place

void Foo(object o){}
Foo( i ); // here too

additionally are there situations of implicit unboxing where programmers
should take care of?
 
i always hear about the dangers (performance loss) that comes with implicit
autoboxing. when are situations where this happens?

Assigning a value type variable to an implemented interface also
causes it to be boxed.

additionally are there situations of implicit unboxing where programmers
should take care of?

No, unboxing is made explicitly.



Mattias
 
thanks for reply.

interfaces are object types too, so i wouldn't wonder about that.
 
Assigning a value type variable to an implemented interface also
causes it to be boxed.

and what about

struct S : ICountable{};

S s;
int i = s.Count; // is this a boxing?

this is imho an implicit conversion to an implemented interface. but does
this mean, that boxing occures?
 
cody said:
and what about

struct S : ICountable{};

S s;
int i = s.Count; // is this a boxing?

this is imho an implicit conversion to an implemented interface.

How? There's no implicit conversion happening anywhere. Interfaces only
provide an interface that should be implemented - structs implementing
interfaces do not imply that structs (value types) implicitly converted
to a reference type.
but does this mean, that boxing occures?

No. Count (I'm guessing) is an integer (and so a value type) and you're
simply copying its value to the variable 'i'. If, in some way, Count is
an object, the line won't compile. Boxing only occurs when you try
assigning a value type to a reference type.


-Andre
--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
 
cody said:
and what about

struct S : ICountable{};

S s;
int i = s.Count; // is this a boxing?

this is imho an implicit conversion to an implemented interface. but does
this mean, that boxing occures?

No, boxing does not occur. Calls only go through the interface when you call
through the interface. If you wrote:

S s;
ICountable ic = s;
int i = ic.Count;

Then there would be boxing.

Another way to look at it is that boxing only occurs when you assign a value
type to object or to an interface.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top