Roslyn: Proposal: Disallow e is null and other constant patterns

Created on 26 Nov 2016  路  8Comments  路  Source: dotnet/roslyn

e is null is a good way for reference null check instead of (object)e == null but it does not work with non-constant expressions e.g. e1 is e2. I think multiple ways of doing the same thing would be (1) confusing for beginners and (2) it would cause yet another inconsistency all over the code base i.e. there should be a code style option to prefer one over the other. I'd rather have a dedicated operator for such operations (#8409) to cover all cases and maintain a consistent behavior instead of an operator that does not cover all cases and essentially is useful in comparing by value scenarios i.e. patterns.

If it's here to stay I'd like to hear the rational behind it.

Area-Language Design Bug Resolution-By Design

All 8 comments

e is null can not be used for reference comparisons because it uses the Object::Equals(object, object) sample

Currently all constant patterns generate that call. It's just not optimized yet. See #13247.

Thanks, nice catch.

Closing per https://github.com/dotnet/roslyn/issues/8409#issuecomment-263097610 as it's the intended usage and probably #8409 would be a non-issue.

I think I closed this prematurely, because still I couldn't think of any good reason to permit constant patterns directly in top level is e.g. e is 3. I believe it's just a syntax variation for e == 3 and may cause unnecessary inconsistencies.

@MadsTorgersen I propose we discuss this (disallowing constant patterns on the right of the is operator) at an upcoming LDM.

@alrz e is 3 is not the same as e == 3, as it can work even when the type of e is object.

Agreed 100%. To me this not only seems like unnecessary complexity, confusion for beginners, more inconsistency and ways to do essentially the same thing, but also like abuse of the is operator which has always meant instanceof in C#, and never any kind of comparison.

The LDM discussed this yesterday and concluded that we intend to support constant patterns in the is operator. The idiom e is null is useful and much nicer than the current alternative (object)e == null.

Was this page helpful?
0 / 5 - 0 ratings