简体   繁体   中英

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

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.

Any reference type (such as classes) will require new. Value types (such as int) are simple values and do not require new.

You do not need to new value types in c#. All other types you do.

Have look to this MSDN documentation on new

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

int myInt = new int();

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

int myInt = 0;

int i值类型 ,这就是为什么你不需要初始化和new List<string>()引用类型 ,你需要为它分配一个对象实例

Reference types must be allocated using new .

Value types do not have to be heap allocated. Integer, Double, and struct types are examples of value types. A value type that is a local var will be stored on the function call stack. A value type that is a field of a class will be stored in the class's instance data.

Simply check the IL: you can see the compiler emits either an 'initobj' or 'newobj'.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM