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

I want to better understand the difference between using "new" to allocate memory for variables and cases when a new one is not required.

When i announce

int i; // I don't need to use new. 

But

 List<string> l = new List<string>(); 

Does it make sense to say "new int ()"?

+4
source share
7 answers

You will need to use new to highlight any reference type (class).

Any type of value (such as int or structs) can be declared without new. However, you can still use new ones. The following are valid:

 int i = new int(); 

Note that you cannot directly access a value type before initializing it. The value of the new TheStructType() often used with the structure, since it allows you to fully use the elements of the structure without explicitly initializing each element. This is because the constructor is initializing. With a value type, the default constructor always initializes all values โ€‹โ€‹to 0.

In addition, with struct, you can use new with a constructor other than the standard, for example:

 MyStruct val = new MyStruct(32, 42); 

This allows you to initialize the values โ€‹โ€‹within the structure. However, it is not required here, only an option.

+6
source

Any reference type (e.g. classes) will require a new one. Value types (e.g. int) are simple values โ€‹โ€‹and do not require new ones.

+3
source

You do not need to create new value types in C #. All other types that you make.

+3
source

Take a look at this MSDN documentation for new

It is also used to call the default constructor for value types, for example:

int myInt = new int ();

In the previous statement, myInt is initialized to 0, which is the default value for the int type. The operation has the same effect as:

int myInt = 0;

+2
source

int i type of the value , so you do not need to initialize, and new List<string>() is the reference type , you need to assign an instance of the object to it

+1
source

Link types must be allocated using new .

Value types should not be heaped. Examples of value types are Integer, Double, and struct. The type of the value, which is the local var, will be stored in the function call stack. The data type, which is the class field, will be stored in the data of the class instance.

+1
source

Just check IL: you can see that the compiler emits either "initobj" or "newobj".

initobj is emitted as for int i = 0; and int i = new int ();

http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(v=vs.85).aspx

+1
source

Source: https://habr.com/ru/post/1380819/


All Articles