MSP.Saami

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...




Re: Visual C# General Is primitive types are ref or value types?

Mike Danes

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.





Re: Visual C# General Is primitive types are ref or value types?

Matthew Watson

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).





Re: Visual C# General Is primitive types are ref or value types?

MSP.Saami

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




Re: Visual C# General Is primitive types are ref or value types?

MSP.Saami

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..






Re: Visual C# General Is primitive types are ref or value types?

JThiloR

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).