开发者

Making a Count that takes into consideration null check - What should i call it? SafeCount?

    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?


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;
}


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜