I want to understand better the difference between using 'new' to allocate memory for variables and the cases when new is not required.
When I declare
int i; // I don't need to use new.
But
List<string> l = new List<string>();
Does it make sense to say "new int()" ?
You will need to use new to allocate any reference type (class).
Any value type (such as int or structs) can be declared without new. However, you can still use new. The following is valid:
int i = new int();
Note that you can't directly access a value type until it's been initialized. With a struct, using new TheStructType()
is often valuable, as it allows you full use of the struct members without having to explicitly initialize each member first. This is because the constructor does the initialization. With a value type, the default constructor always initializes all values to the equivalent of 0.
Also, with a struct, you can use new
with a non-default constructor, such as:
MyStruct val = new MyStruct(32, 42);
This provides a way to initialize values inside of the struct. That being said, it is not required here, only an option.
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