Question

When collection property( of type "IList" or Array), should it be null when there are no elements OR should it be represented as an empty collection (i.e length is zero)

e.g.

public class Teacher
{
  public List<Student> Students = null // to represent absence of items
}

OR

public class Teacher
{
   public List<Student> Students = new List<Student>() // Initialize the collection.
}

What is the best practice around this.

Was it helpful?

Solution

In most cases this should be an empty list. This will simplify your logic since you don't have to do the null checks everywhere you use your list.

For example, if you want to see if the list contain the element "Test", you can do like this:

if (myList.Contains("Test"))

Instead of having to write

if( myList != null && myList.Contains("Test"))

This is also what LINQ does for it's extention methods: Returns an empty IEnumerable if there is no elements, instead of null. That is of course also important to be able to chain those method calls.

There can of course be some circumstances where you would like the list to be null to indicate something specific, but in most cases you are doing yourself a favour by initializing it. You will see a lot less null pointer exceptions that way ;)

OTHER TIPS

They can have quite different meanings, so it's up to you (and your requirements) to decide what is the correct code.

Is a teacher without students (Students = null) the same as a teacher with no students (Students.Count == 0). In database terms, one is the equivalent to the value null for a column, and the other is the value 0.

However, if those cases are equivalent, than IMHO, it's better to do

public List<Student> Students = new List<Student>();

because it will not throw when you do operations like .Count or .Where on the property.

BTW, Do make it a property, public mutable collection fields sure are fun to debug.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top