In C #, why not use the 'new' keyword when declaring int?

When declaring int ..

int A = 10; 

why not do the following instead?

 int A = new Int() A=10; 

are the same?

+4
source share
5 answers

Because int is syntactic sugar for Int32 which is a value type. By the way, the same applies to the constant value 10 (an instance of the value type Int32 ). That is why you do not need to use new to create a new instance, but make a copy of 10 and name it A similar syntax works with reference types, but with the difference that the copy is not made; link created.

Essentially, you can think of 10 as a previously announced Int32 instance. Then int A = 10 is just setting the variable A for a copy of the value 10 (if we were talking about reference types, then for A we would set a reference to the instance instead of the copy).

To better illustrate another example here:

 struct SomeValueType { public SomeValueType(){ } } public static readonly SomeValueType DEFAULT = new SomeValueType(); 

Then you can simply do this:

 SomeValueType myValueType = DEFAULT; // no neeed to use new! 

Now imagine SomeValueType is Int32 and DEFAULT is 10 . Here it is!

+10
source

You may have seen Java, where int and Integer are two different things, and for the latter you need to write new Integer(10) .

C # int has a special alias for Int32 , and they are the same for all purposes and tasks. Indeed, to create a new instance of any type, you need to write new Int32() or something else.

However, since integers are primitive types in C # (and most programming languages), there is a special syntax for integer literals. Just writing 10 makes it Int32 (or int ).

In your example, you actually assign the value of the variable a twice:

 int a = new Int32(); // First assignment, a equals 0 a = 10; // Second assignment, a equals 10 

It can be assumed that since the second assignment overwrites the first, the first assignment is not required.

+7
source

In C # there are two types of types: "reference types" and "value types". (Pointers are the third type type, but don't go into it.)

When you use the default constructor of the value type, all you say is "give me the default value of this value type." Therefore, new int() no more and no less than just saying 0 .

So your program is the same as:

 int i = 0; i = 10; 
+7
source

if you write your code for example

 int A = new Int(); 

the "A" variable is assigned the default value for int, so you can use the "A" variable without assigning it a value (in c# we cannot use the variable without assigning a value to it) when using the new keyword, it will automatically call the default constructor, it will assign default values ​​to variables.

0
source
 int A = new Int(); 

It declares and initializes A to 0 .

Essentially, the new operator here is used to invoke the default constructor for value types. For int, the default value is 0.

This has the same effect as the following:

 int A = 0; 
0
source

All Articles