Default values of class variables

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?

Upvotes: 4

Views: 5172

Answers (2)

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.

Upvotes: 8

Christos
Christos

Reputation: 53958

A List<T> where T is any type is a reference type. Hence, it's default value is null.

For instance let that we have the following class declaration:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName  { get; set; }
    public List<Order> Orders { get; set; }
}

where Order is a class.

If you instantiate an object of type customer like below:

var customer = new Customer();

Then

customer.Id // is 0
customer.FirstName // is null
customer.LastName // is null
customer.Orders // is null

Note that both FirstName and LastName are strings and their default value is null. Strings are reference types.

Upvotes: 5

Related Questions