-
Notifications
You must be signed in to change notification settings - Fork 4
Gendarme.Rules.BadPractice.PreferEmptyInstanceOverNullRule(2.10)
Sebastien Pouliot edited this page Jan 22, 2011
·
2 revisions
Assembly: Gendarme.Rules.BadPractice
Version: 2.10
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.
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;
}
}
- This rule is available since Gendarme 2.4
Note that this page was autogenerated (3/17/2011 9:31:58 PM) based on the xmldoc
comments inside the rules source code and cannot be edited from this wiki.
Please report any documentation errors, typos or suggestions to the
Gendarme Mailing List. Thanks!