2

I want to be able to know which methods return null from .NET Framework.

For example; when I call a search method from IQueryable, if the search did not find any results will it return null or an empty collection.

We learn some of the methods but when new methods are concerned, I always write additional line of codes which makes harder to read the code.

Is there an easy way to work off this?

EDIT:

How I always encounter this problem is like this:

List<int> ints = new List<int>(); // Suppose this is a list full of data

// I wanna make sure that FindAll does not return null
// So getting .Count does not throw null reference exception
int numOfPositiveInts = ints.FindAll(i => i > 0).Count;

// This is not practical, but ensures against null reference return
int numOfPositiveInts = ints.FindAll(i => i > 0) != null ? ints.FindAll(i => i > 0).Count : 0;

First option is practical but not safe, while second option prevents any null reference exceptions but decreases readability.

Thanks.

Rob
  • 4,927
  • 12
  • 49
  • 54
Mert Akcakaya
  • 3,109
  • 2
  • 31
  • 42
  • If method returns type that is ValueType it can't be null, if it's referenceType it can be null or I misunderstood your question. – Leri Jul 19 '12 at 12:52
  • Most methods specify in the description when they return null. For example, `Where` never returns null. `SingleOrDefault` will return the single element if `Count()==1`, default value (null in case of a reference value, 0 or false for primitives) if no elements, and throws an exception if more then one element exists. – Mark Segal Jul 19 '12 at 12:52
  • @PLB, Is it always true that if the method return type is reference type, it may return null? I think some of the methods returning references (especially Collection types) return empty collections instead of null reference. – Mert Akcakaya Jul 19 '12 at 13:00
  • @Mert returning reference type means that it might be null so it's a good idea to check if object is null. If you've seen inner implementation of method and you are sure that it won't be null you don't have to check agains null-s. If you want to know what's the exact return of methods read official .NET documentation. If you use libraries written by other programmers and you're not able to take a look what's inside always check for nulls. – Leri Jul 19 '12 at 13:10
  • @PLB, I couldn't find any information about null reference returns in the documentation. Can you check my edit please? – Mert Akcakaya Jul 19 '12 at 13:34
  • @Mert With `FindAll()` you don't need to ensure against nulls. – Leri Jul 19 '12 at 13:55
  • @PLB, Great, can we take this as a general rule for all methods that return collection types? – Mert Akcakaya Jul 19 '12 at 14:15

1 Answers1

1

When you install Code Contracts there are auxiliary assemblies installed that give you the Contracts for most of the core library. There is an editor plugin that shows them in IntelliSense style.

H H
  • 263,252
  • 30
  • 330
  • 514