Reputation: 4385
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()" ?
Upvotes: 4
Views: 442
Reputation: 8792
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
Upvotes: 1
Reputation: 564413
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.
Upvotes: 6
Reputation: 4683
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;
Upvotes: 2
Reputation: 36082
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.
Upvotes: 1
Reputation: 3277
You do not need to new value types in c#. All other types you do.
Upvotes: 3
Reputation: 3381
Any reference type (such as classes) will require new. Value types (such as int) are simple values and do not require new.
Upvotes: 3
Reputation: 19217
int i
is value type that's why you don't need to initialize and new List<string>()
is reference type, you need to assign an object instance to it
Upvotes: 1