Click here to Skip to main content
15,900,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I used to think that reference type cannot contain valuetype.....Please help.
question-
if int a=15 is value type. and
int b=new int() is reference type.
Then why b=a is allowed????


Please help.
Posted

C#
int b=new int();
Does not create a reference type - it creates a value type. int is always a value type, the new int() syntax is just allowed for completion, it does not create any new allocation on the heap, and does not return a reference.
If you have a look at the IL it generates the same code:
C#
int A = new int();
int B = 0;

.locals init ([0] int32 A,
              [1] int32 B)
IL_0000:  nop
IL_0001:  ldc.i4.0
IL_0002:  stloc.0
IL_0003:  ldc.i4.0
IL_0004:  stloc.1
 
Share this answer
 
Comments
vicvis 13-Jan-13 8:52am    
Thanks a lot.I thought new is always used for reference type.I think i must study new a bit more about new operator.
Thanks for your answer and guiding to right direction.
OriginalGriff 13-Jan-13 9:25am    
You're welcome!
int b = new int() is not a reference type, it is the same as saying int b = 0; Just because the new operator is used does not mean you are getting a reference type.
That being said, int[] b = new int[10] does result in a reference type on the array object itself, but each of the members are still value types.

For a better explanation, see MSDN Documentation here[^].
MSDN: Value Types[^]
 
Share this answer
 
Comments
vicvis 13-Jan-13 8:53am    
Thanks for your answer and guiding to right direction.I think i must study new a bit more about new operator.

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