4

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?

2
  • 7
    strings will be null, not "". Commented Apr 11, 2015 at 21:54
  • 1
    If you want your class members to default to something else every time you declare an instance of a class, you can do so in the constructor of the class. Commented Apr 11, 2015 at 21:58

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.