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.FirstOrDefaultEnumerable.SingleOrDefaultEnumerable.LastOrDefaultEnumerable.ElementAtOrDefaultNullable.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)
加载中,请稍侯......
精彩评论