roslynator
roslynator copied to clipboard
New Analyzer with Fix Request: consistent property access for potentially null object
Product and Version Used: Roslynator Analyzers (New as-of 2.1.0)
Before
Person person = // ... call that obtains a Person that could be null
DoSomething(
person?.FirstName, // <-- Since this uses ?. it means person could be null
person.LastName); // <-- this should also use ?. to avoid a NullReferenceException
After
Person person = // ... call that obtains a Person that could be null
DoSomething(
person?.FirstName,
person?.LastName);
The scope with a method call is obvious, but it seems like this should be applicable across various scopes where 'person' is not reassigned. Also, this could be triggered by other expressions that indicate that a null is possible -- for instance:
Before / Alternate Scope Example
Person foo = person ?? defaultPerson; // <-- the use ?? implies that person could be null
string str = person.ToString(); // <-- when person is null above, this could throw NullReferenceException
After Fix
Person foo = person ?? defaultPerson;
string str = person?.ToString();
(edited request to revise formatting.)
I note that the examples in my request are simplistic. Production-code is likely to contain complexities that would render doing this analyzer & fix in a robust/comprehensive manner difficult or impractical. However, working for the simplest scenarios like simple property access that I show in the method call could still be immensely useful.