DEV Community

Discussion on: No more NullReferenceException for Lists in C#

 
aaronincincy profile image
Aaron Johnson

I feel like you're being intentionally obtuse about this when everyone else has provided great arguments in favor of always-initializing collections.

To play your game, here's an example:


class LibraryVisitor {
  private List<Book> CheckedOutBooks { get; set; }
  private string MemberNumber { get; set; }

  public void CheckOut(Book book) {
    CheckedOutBooks.Add(book);
  }

  public void Register(memberNumber) {
    MemberNumber = memberNumber;
    CheckedOut = new List<Book>();
  }
}

This is obviously shit code (arguably no worse than your examples), but the premise is I shouldn't be able to check out a book until I've registered.

A reasonable fix to this code would be:


class LibraryVisitor {
  private List<Book> CheckedOutBooks { get; } = new List<Book>();
  private string MemberNumber { get; }

  public void CheckOut(Book book) {
    if (MemberNumber == null) {
      throw new NotRegisteredException();
    }

    CheckedOutBooks.Add(book);
  }

  public void Register(memberNumber) {
    MemberNumber = memberNumber;
  }
}
Thread Thread
 
alialp profile image
Ali Alp

When you don't get , you don't get it.
let me demistify once more.
The conventional methods which any junior developer should be aware are crystal clear . The issue is why when you are trying to add to a list which is a member of a class and you already instantiated the class should throw an exception ?
It should instanciate the list object on the first add itself.