views:

74

answers:

2
    public static int SafeCount<T>(this IList list)
    {
        return list != null ? list.Count : 0;
    }

What I want to ask is what should I call this method? SafeCount? NullSafeCount?

Can you come up with something more short yet non-ambigous?

A: 

It might just be linq's influence on me, but I would be tempted to call it 'CountOrDefault'. Not really shorter though...

(side note: Why IList and not IEnumerable? Just curious)

diceguyd30
I'll have to count.
halviingston
In that case you can use IEnumerable's Count() Function. I can understand not wanting to materialize the IEnumerable, but you have to do that anyway to create the IList necessary to use the above function.
diceguyd30
One possible shorter name: 'CountOr0'
diceguyd30
+2  A: 

To align with other methods in the framework I would call it GetCountOrDefault or possible CountOrDefault. Similar methods from which I would look to for predecence.

  • Enumerable.FirstOrDefault
  • Enumerable.SingleOrDefault
  • Enumerable.LastOrDefault
  • Enumerable.ElementAtOrDefault
  • Nullable.GetValueOrDefault

Another option is to encode the ambiguity in the return type instead of the method name by having it return a int? instead of an int.

public static int? GetCount(this IList list) { 
  return list != null ? (int?)list.Count : null;
}
JaredPar
I see where you're going with this .. hmm don;t know how I Feel about it thoiugh.
halviingston
@halviingston, I agree it's a bit odd at first. But without a compelling reason I would favor precedenc over a new name. In these examples the `Nullable<T>` is the most compelling for me as it describes a very similar scenario.
JaredPar
@halviingston added another suggestion.
JaredPar