Roslyn: 'Generate Equals' should use `is object` rather than `!= null`

Created on 12 Oct 2019  路  4Comments  路  Source: dotnet/roslyn

Mentioned by @sharwell at https://github.com/dotnet/roslyn/pull/39242#discussion_r334215178.

My own awareness of is object began at https://twitter.com/jaredpar/status/1115019017297596416:

Think developers should embrace is object as the canonical non-null test in C#. It works in every version, won't compile when the expression type is a struct, logical opposite of is null, emits efficient IL, ... the only fault you can say is the name isn't obvious.

https://twitter.com/jaredpar/status/1171474157667643400:

Another developer converted to "x is object" as the canonical null check in C#. If I have to go dev by dev to achieve correctness then so be it.

(@jaredpar hope you don't mind me referencing your feed...)

After the 9.0 candidate https://github.com/dotnet/csharplang/issues/1350 makes it into the language, I believe the canonical non-null test will be is not null.

Area-IDE Concept-Continuous Improvement IDE-CodeStyle help wanted

Most helpful comment

I would wait until we get to that point before making any changes here.

Sam pointed out that the current other != null check is calling into the generated != operator which calls into the generated == operator. This doesn't seem awesome.

Thankfully the generated code for == is EqualityComparer<T>.Default.Equals(left, right) and the thing keeping it from recursing is that it only calls IEquatable<T>.Equals if neither left nor right are null.

All 4 comments

I believe the canonical non-null test will be is not null.

I would wait until we get to that point before making any changes here.

We already implemented is object for other not-null checks in refactoring. This is just a consistency fix.

I would wait until we get to that point before making any changes here.

Sam pointed out that the current other != null check is calling into the generated != operator which calls into the generated == operator. This doesn't seem awesome.

Thankfully the generated code for == is EqualityComparer<T>.Default.Equals(left, right) and the thing keeping it from recursing is that it only calls IEquatable<T>.Equals if neither left nor right are null.

Even on older language/framework, ReferenceEquals(other, null) still gives better performance with readability.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AdamSpeight2008 picture AdamSpeight2008  路  3Comments

asvishnyakov picture asvishnyakov  路  3Comments

codingonHP picture codingonHP  路  3Comments

marler8997 picture marler8997  路  3Comments

glennblock picture glennblock  路  3Comments