Returning Null or an Empty Collection


Returning Null or an Empty Collection

When returning an array or collection, you must indicate that there are zero items by returning either null or a collection instance with no items. The better choice in general is to return a collection instance with no items. In so doing, you avoid forcing the caller to check for null before iterating over the items in the collection. For example, given a zero-size IEnumerable<T> collection, the caller can immediately and safely use a foreach loop over the collection without concern that the internal call to GetEnumerator() will throw a NullReferenceException.

One of the few times to deviate from this guideline is when null is intentionally indicating something different from zero items. A null value for a phone number on a string, for example, may indicate that the phone number is not set, and an empty string could indicate explicitly that there is no phone number.




Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net