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.
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 ;)