I have a class called Division that contains information about Subdivisions (in an internal List), including a classification code for each subdivision. In the Subdivision class, the code is stored as an int. In the Division class, a List is used to store all the codes. On occasion, there will be a Division with no Subdivisions, hence no codes. Or, for whatever reason, a code may not have been set for a Subdivision. So it will have a default value of 0. I don’t want to return a list unless it has actual codes.
public List<int> AllCodesList
{
get
{
return (from subdivision in SubdivisionInfoList
where subdivision.code > 0
select subdivision.code).ToList();
}
}
Returning empty list instead of null is generally good idea as the calling code can be much simple – no need to check for null (which will be missed from time to time and cause infamous null pointer exception).
There are cases when one is interested in distinction between empty list and null, but I’d strongly recommend to review such calls and make sure method’s name is clear on what would be returned, some refactoring may help to never return null. In you particular case I think returning empty array in case of “no subdivisions” is perfectly fine.