Is primitive types are ref or value types?  
Author Message
MSP.Saami





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

Hi,

we can call new operator on primitive types, such as-

int age=new int();

but we all know that int is an alias for System.Int32 STRUCTURE, and also we know that structures are of *VALUE* types.

from this I came to understand that *age* is of value type although *new* operator is called, becoz it is structure.

But, I read that the abov declaration is a *REFERENCE* type.

I need solution to this and your idea pls frendz.

have a nice day...




Visual C#14  
 
 
Mike Danes





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

It's simple: new works with both value types and reference types. For reference types it allocates memory for them and calls the constructor while for value types it just calls the constructor. In the particular case of int and other primitive types the constructor is not even called, the compiler simply generates code that loads the age variable with 0.

"But, I read that the abov declaration is a *REFERENCE* type."

Where did you read that It's not correct, int and all other primitive types are value types.


 
 
Matthew Watson





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

They are value types. What "new int()" does is return a default VALUE for an int.

You could also do "int age = default(int);" or (preferably) "int age = 0;"

These all have the same effect (and generate identical IL code).


 
 
MSP.Saami





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

I read in, C# :The complete Reference and I am not willing to say the name of author.

 
 
MSP.Saami





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

ok...

Then why we need to convert primitive types to reference types, that is Boxing ..... I dont seem there is no any special use of converting primitive to reference type... your idea in this regard..



 
 
JThiloR





PostPosted: Visual C# General, Is primitive types are ref or value types? Top

One reason for using boxing is to work with Collections (without generics). There you like to have abstract containers for every type (object) and so you have to box your ints into objects. Normally you don't want to box (poor performance and runtime errors), so use Generics (> .NET 2.0).