I'm currently working on a class which exposes an internal List through a property. The List shall and can be modified. The problem is, entries in the internal list could be set to null from outside the class.
My code actually looks like this:
class ClassWithList
{
List<object> _list = new List<object>();
// get accessor, which however returns the reference to the list,
// therefore the list can be modified (this is intended)
public List<object> Data
{
get
{
return _list;
}
}
private void doSomeWorkWithTheList()
{
foreach(object obj in _list)
// do some work with the objects in the list without checking for null.
}
}
So now in the doSomeWorkWithTheList() I could always check whether the current list entry is null or I could just asume that the person using this class doesn't have the great idea to set entries to null.
So finally the questions end up in: Whose fault is a NullReferenceException in this case? Is it the fault of the class developer not checking everything for null (which would make code generally - not only in this class - more complex) or is it the fault of the user of this class, as setting a List entry to null doesn't really make sense? I'd tend to generally not check values for null except in some really special cases. Is this a bad style or de facto standard / standard in praxis?
I know there's probably no ultimate answer for this, I'm just missing enough experience for such thing and therefore wondering what other developers think about such cases and want to hear what's done in reality about checking null (or not).