-1

Are there any arguments against throwing inside the implementation of IComparable<T>.CompareTo(T value) ?

Does it make sense that Nullable<T>.Compare(null, notNullValue) doesn't throw and why ?

sm_
  • 2,572
  • 2
  • 17
  • 34
  • 1
    throw what? exception ? – TimChang Oct 04 '19 at 05:17
  • We're talking about `null`s, right? Well, as of C# 8, instead of `throw`ing, just add a `where T: notnull` constraint on your type that implements `IComparable` – CoolBots Oct 04 '19 at 05:21
  • 1
    The important thing about `IComparable` is that you follow the rules. They can be summed up roughly as "follow the trichotomy law of order" (if A – Flydog57 Oct 04 '19 at 05:21
  • Throwing on null in a `IComparable.CompareTo` is like leaving a big undocumented gotcha to your work mates in your code IMO – TheGeneral Oct 04 '19 at 05:24
  • @TheGeneral care to elaborate more maybe with an example ? – sm_ Oct 04 '19 at 05:26
  • @CoolBots super cool find, however i'm more concerned with types that i want to be nullable – sm_ Oct 04 '19 at 05:33

1 Answers1

2

The reasons for not throwing are that it's not needed and that the signature of IComparable.CompareTo(T) Method doesn't specify any exceptions, so you'd break the contract.

(BTW. IComparable.CompareTo(Object) Method does allow ArgumentExecption).


Does it make sense that Nullable.Compare(null, notNullValue) doesn't throw and why ?

Yes it makes sense not to throw, as null value has its place in the order of things. For example if you have a nullable column in the database you can still order it. In SELECT - ORDER BY Clause (Transact-SQL) you can read:

ASC | DESC

Specifies that the values in the specified column should be sorted in ascending or descending order. ASC sorts from the lowest value to highest value. DESC sorts from highest value to lowest value. ASC is the default sort order. Null values are treated as the lowest possible values. [emphasis mine]

tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Shouldn't the meaning of Null or something of an undefined value be a domain concern rather than defaulting to a framework or SQL standard ? – sm_ Oct 07 '19 at 23:00