Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values of class variables

Tags:

c#

class

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?

like image 858
Taşyürek Gökşah Avatar asked Dec 11 '22 00:12

Taşyürek Gökşah


1 Answers

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 elements

The 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.

like image 195
Ian Kemp Avatar answered Dec 30 '22 17:12

Ian Kemp