Skip to content

Gendarme.Rules.BadPractice.PreferEmptyInstanceOverNullRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

PreferEmptyInstanceOverNullRule

Assembly: Gendarme.Rules.BadPractice
Version: 2.10

Description

This rule checks that all methods and properties which return a string, an array, a collection, or an enumerable do not return null. It is usually better to return an empty instance, as this allows the caller to use the result without having to perform a null-check first.

Examples

Bad example (string):

public string DisplayName {
    get {
        if (IsAnonymous) {
            return null;
        }
        return name;
    }
}

Good example (string):

public string DisplayName {
    get {
        if (IsAnonymous) {
            return string.Empty;
        }
        return name;
    }
}

Bad example (array):

public int [] GetOffsets ()
{
    if (!store.HasOffsets) {
        return null;
    }
    store.LoadOffsets ();
    return store.Offsets;
}

Good example (array):

static const int [] Empty = new int [0];
public int [] GetOffsets ()
{
    if (!store.HasOffsets) {
        return Empty;
    }
    store.LoadOffsets ();
    return store.Offsets.ToArray ();
}

Bad example (enumerable):

public IEnumerable<int> GetOffsets ()
{
    if (!store.HasOffsets) {
        return null;
    }
    store.LoadOffsets ();
    return store.Offsets;
}

Good example (enumerable):

public IEnumerable<int> GetOffsets ()
{
    if (!store.HasOffsets) {
        yield break;
    }
    store.LoadOffsets ();
    foreach (int offset in store.Offsets) {
        yield return offset;
    }
}

Notes

  • This rule is available since Gendarme 2.4
Clone this wiki locally