Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: What data types require NEW to allocate memory?

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()" ?

like image 937
user776676 Avatar asked Dec 04 '22 06:12

user776676


1 Answers

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.

like image 69
Reed Copsey Avatar answered Dec 16 '22 22:12

Reed Copsey