Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Int32() usages in c#?

C# compiler allows me to write :

int k=new Int32();

However , I can't assign any value to it.

2 questions

1) doesnt new create a Heap allocation , and if so , what about the stack<->value thing ?

2)I can't do nothing with int k=new Int32();. in what scenarios will I use it ?

like image 939
Royi Namir Avatar asked Nov 24 '12 07:11

Royi Namir


People also ask

What's Int32?

Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32. MinValue constant) through positive 2,147,483,647 (which is represented by the Int32. MaxValue constant. .

What does Int32 do in C#?

In C#, Int32 Struct represents 32-bit signed integer(also termed as int data type) starting from range -2,147,483,648 to +2,147,483,647. It also provides different types of method to perform various operations. You can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int32 type.

Is int Int32 C#?

Int32 is a type provided by . NET framework whereas int is an alias for Int32 in C# language.

What is int and Int32?

Int32 is 32 bit, while int is 64 bit; int is 32 bit integer on 32 bit platform, while it is 64 bit on 64 bit platform; int is value type, while System.


1 Answers

All structs (and int/Int32 is a struct) allow new() usage, which just means: initialise the struct to default values, I.e. zero for all fields in the struct. Most structs are immutable - and primitives certainly are. Basically, what you have written is the same as:

int k=0;

You can do lots of things with that.... But you can't change any properties of zero. Zero is zero is zero.

new does not always mean "allocate on the heap".

like image 57
Marc Gravell Avatar answered Sep 29 '22 07:09

Marc Gravell