Just curious, what is the difference between:
int A = 100;
and
int A = new int();
I know new is used to allocate memory on the heap..but I really do not get the context here.
Creates a integer array of 'n' elements.
There is no difference between the two of them. But you should never instintiate your value types with the 'new' keyword.
new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.
*new int means "allocate memory for an int , resulting in a pointer to that memory, then dereference the pointer, yielding the (uninitialized) int itself".
static void Main() { int A = new int(); int B = default(int); int C = 100; Console.Read(); }
Is compiled to
.method private hidebysig static void Main() cil managed { .entrypoint // Code size 15 (0xf) .maxstack 1 .locals init ([0] int32 A, [1] int32 B, [2] int32 C) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: stloc.0 IL_0003: ldc.i4.0 IL_0004: stloc.1 IL_0005: ldc.i4.s 100 IL_0007: stloc.2 IL_0008: call int32 [mscorlib]System.Console::Read() IL_000d: pop IL_000e: ret } // end of method Program::Main
As you can see first one just initialize it and second one is just the same and third one initialize and set to 100
. As for the IL code generated, they both get initialized in a single line.
so
int A = new int();
Is the same as
int A = default(int);
Difference?
the latter ends with A being 0, not 100.
When?
Pretty much never. Maybe in some generated code it is simpler to use the new TypeName()
syntax, but default(TypeName)
would be preferred even then.
And new
does not "allocate memory on the heap". It initializes an instance; that is all.
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