Reputation: 10766
When specifying and creating numeric functions are there any C# idiomatic guidelines on when to return null and when to return NaN when both seem valid outputs.
The concrete example that has lead to this question is I am creating a percentage extension method for Enumerable collections. I have been thinking about what to return if there is an empty input. The function could return runningCount / totalCount which would return NaN on zero length inputs. However, I am not convinced that this sits well with the general feel of the language.
Are there any guidelines or language examples could inform the decision whether to retun NaN or null.
Upvotes: 2
Views: 932
Reputation: 942297
Idiomatic C# code throws exceptions when it is asked to do something that doesn't make sense. Like calculating a percentage on empty input. That ought to be an InvalidOperationException.
Returning magic values like null or NaN tends to just cause more trouble when the client code doesn't check for it. It won't, it also didn't check that the input was empty so it won't expect them. Null is nasty for the nondescript NullReferenceException it generates, giving no hint to what the real problem might be. NaN is nasty for just propagating undetectably, turning everything into NaN and ultimately generating nonsense results that you can't trace back to the source.
Upvotes: 3
Reputation: 354804
You might want to look in what ways your extension method might be used. NaN
is a perfectly valid double
value and thus can be used to perform calculations with (well, the result of those will always be NaN
, but at least you won't get an excetion). If your context requires checking the result before using it anyway, then you might want to opt for null
.
However, what Andre already commented, for a percentage of an empty collection (which might result if there are no items yet) 0
might be a more sensible return value.
Upvotes: 1