Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in C#, why not use 'new' keyword when declaring an int?

Tags:

c#

int

When declaring an int..

int A = 10;

why not do the following instead?

int A = new Int()
A=10;

are both the same?

like image 723
user1034912 Avatar asked Mar 21 '13 23:03

user1034912


1 Answers

Because int is syntax sugar for Int32 which is a value type. Incidentally, so is the constant value 10 (an instance of the value type Int32). That's why you don't need to use new to create a new instance, but rather making a copy of 10 and calling it A. And similar syntax works with reference types as well, but with the difference that a copy isn't made; a reference is created.

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

To better illustrate here's another example:

struct SomeValueType {
    public SomeValueType(){        
    }
}

public static readonly SomeValueType DEFAULT = new SomeValueType();

Then you can just do this:

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

Now imagine that SomeValueType is Int32 and DEFAULT is 10. There it is!

like image 76
Mike Dinescu Avatar answered Sep 24 '22 23:09

Mike Dinescu