Click here to Skip to main content
16,020,347 members
Please Sign up or sign in to vote.
2.59/5 (3 votes)
See more:
I understood
C#
int i = 123;
object o = (object)i;  // boxing
o = 123;
i = (int)o;  // unboxing


But how to I box and unbox if I have something like
C#
int i = 123;
int y;
MyObject obj = new MyObject():
Posted
Comments
gggustafson 3-May-14 23:24pm    
Are you sure you supplied all the code?
RalvarezHose 3-May-14 23:31pm    
I have these codes.

Console.Writeline("i = {0\t obj = {1}", i ,obj);
obj *=2;
gggustafson 3-May-14 23:44pm    
Are you sure it shouldn't be

Console.Writeline ( "i={0}\tobj={1}", i, obj );

Then, why are you concerned about boxing in the first place. The compiler does that for you.
RalvarezHose 4-May-14 0:13am    
I am really sorry but I am having hard time understanding this. Can you explain little bit more, how compiler does it by itself.

1 solution

The question makes no sense because you did not explain what to box and unbox in second case, did not show the definition of the type MyObject and did not explain what you want to exist. If this type is a value type, you can box it by assigning to some object variable; if not, the sample is unrelated to boxing, and, in both cases, the code has nothing to do with i or y.

In first sample, the type cast object o = (object)i; is totally redundant, should be o = i; this is because everything is object, including i.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900