When declaring an int..
int A = 10;
why not do the following instead?
int A = new Int()
A=10;
are both the same?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With