Today i read an answer in this site. MVC ViewModel - Object Reference Not Set to Instance of an Object
I'm confused about default values of instanced classes. When we create a new class by using "new" keyword, its fields's values automatically setted to their default values.
For example integers goes to 0 and strings goes to null.
What about the Lists?
List<int>
Why we dont have new instance of the List belong to the instanced object?
Why we dont have new instance of the List belong to the instanced object?
As per the C# specification, ECMA-334, section 12.2:
The following categories of variables are automatically initialized to their default values:
- Static variables
- Instance variables of class instances
- Array elementsThe default value of a variable depends on the type of the variable and is determined as follows:
- For a variable of a value-type, the default value is the same as the value computed by the value-type's default constructor.
- For a variable of a reference-type, the default value is null.
Refer to the bolded excerpt above - since List<int>
is a reference type, it is therefore initialized to null
.
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