سؤال

I have a small doubt regarding Boxing and Unboxing in C#.

int i=1;
System.Int32 j = i;

above code can be called as boxing?

هل كانت مفيدة؟

المحلول

No, that's not boxing at all. int is just an alias for System.Int32. That code is equivalent to:

int i = 1;
int j = i;

For boxing to occur, there has to be a conversion to a reference type, e.g.

int i = 1;
object j = i;

Or:

int i = 1;
IComparable j = i;

نصائح أخرى

Just to extend Jon's answer just a little bit, boxing will also occur, when you call non-overridden or non-virtual methods of the base class also, like

i.GetType(); //boxing occur here

or pass int to a method, which requires a reference type

void Foo(object obj) {}

Foo(i); //boxing, no overload takes an int

In the first example IL you can clearly see box instruction

int i = 5;
i.GetType();

IL_0000:  ldc.i4.5    
IL_0001:  stloc.0     // i
IL_0002:  ldloc.0     // i
IL_0003:  box         System.Int32    //<---- boxing
IL_0008:  call        System.Object.GetType

If you don't override virtual methods in your value types, they will also be boxed when calling them

enum MyEnum {}

var e = new MyEnum();
e.ToString(); //box will occur here, see IL for details

IL_0000:  ldc.i4.0    
IL_0001:  stloc.0     // e
IL_0002:  ldloc.0     // e
IL_0003:  box         UserQuery.MyEnum
IL_0008:  callvirt    System.Object.ToString

The same situations with structs, except they will use callvirt opcode, that will box the struct if nessecary,

No. int is a value type.

Boxing occurs when you assign a value type to an Object.

It is not boxing.

int is an alias for System.Int32. So your code is equavalent to;

int i = 1;
int j = i;

For boxing, there should be a conversion to an object or an interface. Like;

int i = 1;
object j = i;

A value of a class type can be converted to type object or to an interface type that is implemented by the class simply by treating the reference as another type at compile-time. Likewise, a value of type object or a value of an interface type can be converted back to a class type without changing the reference (but of course a run-time type check is required in this case).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top