IDE0029 Null check can be simplified C# 6.0 ASP.NET
string varIP = Request.UserHostAddress != null ? Request.UserHostAddress : "IP null";
Can be re-written with the null-coalescing operator:
string varIP = Request.UserHostAddress ?? "IP null";
This will use the value of UserHostAddress
, unless it is null in which case the value to the right ("IP null") is used instead.
If there is any possibility of Request
being null, you can additionally used the null-conditional operator that you mentioned in the question:
string varIP = Request?.UserHostAddress ?? "IP null";
In this case if the Request
is null then the left hand side will evaluate as null, without having to check UserHostAddress
(which would otherwise throw a NullReferenceException
), and the value to the right of the null-coalescing operator will again be used.
You can use the null-conditional operator along with null-coalescing operator (??
) to simplify your code:
string varIP = Request?.UserHostAddress ?? "IP null";
it means
if Request?.UserHostAddress
is not null then it will assign the Request.UserHostAddress
value to varIP
,
else "IP null"
is assign to varIP
Visual Studio will automatically change this for you.
First, go to the offending line (you can double-click the message in the Errors List to do this). You'll see that there are 3 dots underneath Request
- this means that a refactoring is available:
There's also a yellow lightbulb in the margin. Click the lightbulb:
You can see the change that Visual Studio suggests. Click "Use coalesce expression" to make the change:
You can also use the shortcut ctrl+.
to do the same thing with less clicking. With your cursor somewhere (anywhere) on that click, press ctrl+.
, and the same menu appears as if you had clicked the lightbulb. Press Enter
to accept the change.
This means you can quickly fix your code:
- Double-click the message in the Errors List
Ctrl+.
thenEnter
Refactorings are available in lots of places, as indicated by the lightbulb. Sometimes you have to have your cursor in a particular place, which makes it hard to discover what's on offer. For example there are refactorings available to automatically implement constructors or generate fields/properties, automatically assign parameters to properties and add null checks, turn foreach loop into for loop and linq, and vice versa, and many many more.