Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a null check cause an equality constraint in F#?

If a generic type is compared with null (and only with null), this causes the compiler to constrain the type both as nullable (which is ok) and as equatable.

Why the latter? It seems that just comparing with null should be ok for types that are nullable, but don't support equality.

I know I can use Unchecked.equals to get just the nullable constraint, just wondering if I'm missing some obvious reason why ((=) null) needs an equatable argument.

like image 940
Kurt Schelfthout Avatar asked Oct 26 '12 13:10

Kurt Schelfthout


1 Answers

The (=) operator has type 'a -> 'a -> bool when 'a : equality. Thus any use of the operator will constrain the type of its arguments to support equality. While it's true that this is technically an unnecessary restriction when you're comparing against the null literal, I think it's reasonable that the compiler just uses its normal inference procedure rather than treating it as a special case.

Note that you can always use obj.ReferenceEquals(x, null) instead if the added constraints are objectionable.

like image 87
kvb Avatar answered Nov 15 '22 07:11

kvb