Use null coalescing in many more places#71361
Conversation
|
Tagging subscribers to this area: @dotnet/area-meta Issue DetailsI previously enabled all of the IDExx rules around null coalescing, but that still left a large number of manual checks in the codebase, so here I used regexes to find and fix up many more occurences. @mavasani, is there an analyzer/fixer for this, or if not, have we considered one? For the most part, this is style, cleaning up around 5K lines, but a non-trivial number do result in more efficient accesses.
|
|
@stephentoub We don't support such an analyzer/code fix/refactoring, but we do have a tracking issue for this feature request: dotnet/roslyn#32985. @CyrusNajmabadi @mikadumont do you know if we have received requests for this feature in the past? |
|
The only reason we didn't do this was because we weren't certain the semantics were identical, and we were worried about power. E.g. the code before only assigns in the case of null. The code after always assigns. If ST is ok with this though, then that's a strong indication this is fine and we should just do this :-) |
Wait, what? _obj ??= new object();is not the same as: _obj = _obj ?? new object();I'd object if it were the latter, but it's actually: if (_obj is null)
{
_obj = new object();
} |
|
That's fascinating. I missed that in the spec:
Thanks for making me aware of that. We'll def add this now! |
|
Updated analyzer/fixer here: dotnet/roslyn#62191 |
| modifier_spec = new List<IModifierSpec>(); | ||
| modifier_spec.Add(md); | ||
| } | ||
| private void AddModifier(IModifierSpec md) => modifier_spec ??= new List<IModifierSpec>(); |
There was a problem hiding this comment.
@stephentoub was it intentional that you also removed the Add call?
There was a problem hiding this comment.
Definitely not. Sorry. I'll fix.
I previously enabled all of the IDExx rules around null coalescing, but that still left a large number of manual checks in the codebase, so here I used regexes to find and fix up many more occurences. @mavasani, is there an analyzer/fixer for this, or if not, have we considered one? For the most part, this is style, cleaning up around 5K lines, but a non-trivial number do result in more efficient accesses.