Roslyn: Analyzer should warn on identifiers named underscore

Created on 3 May 2018  路  9Comments  路  Source: dotnet/roslyn

Like var and nameof, the compiler gives two meanings to _ depending if one was already declared. This can be ambiguous.
Such an analyzer would help customers avoid the ambiguity and only use _ for discards.

This should probably be turned off by default to avoid compat issue. (Update: Cyrus recommends turning it on as suggestion instead).

We may also want to discuss this in context of warning waves.

We probably want to warn on usage (not declaration) of variables named underscore. That way, we won't warn on _ => M(out _) or _ => 1.

Area-IDE Feature Request New Feature - Warning Waves

Most helpful comment

This should probably be turned off by default to avoid compat issue.

I disagree. It should probably be on, but as a suggestion.

I also agree with david, this should help encourage people to move away from 'var' or 'nameof'. If someone does not want that, they can def just suppress, or just disable the analyzer.

All 9 comments

Could that analyser warn on using var, nameof etc too, or is that broadening the scope too much?

This should probably be turned off by default to avoid compat issue.

I disagree. It should probably be on, but as a suggestion.

I also agree with david, this should help encourage people to move away from 'var' or 'nameof'. If someone does not want that, they can def just suppress, or just disable the analyzer.

More specifically, the analyzer should warn on the use of an identifier named _.

Also the analyzer could warn on the following:

// diagnostic
var _ = expression;

// use this instead:
_ = expression;

... and syntax coloring should color it as keyword as it does already for var and nameof.

... and syntax coloring should color it as keyword as it does already for var and nameof.

Back in 2017 previews, use of _ as a discard was colored as a keyword. Why was that removed in the first place?

We still color _ as a discard when it is used as a discard. We color it as an identifier when it is used as an identifier.

@sharwell That's not what it looks like to me:
DiscardDoubts

Nice, it works for out var _ but doesn't work for out _. That's a bug.

@Joe4evr I filed #39768 for the case you mentioned

Was this page helpful?
0 / 5 - 0 ratings