In my visual studio 2017, there is a message in Error List windows like this.
IDE0029 Null check can be simplified
I google it and found this link Null-conditional operators ?. and ?[] but i don't understand.
My code is simple like this:
string varIP = Request.UserHostAddress != null ? Request.UserHostAddress : "IP null";
How to simplify it again?
Any() internally first checks that if the source is null , if so, throws an ArgumentNullException (Does not return a bool in this case). Otherwise, it attempts to access the underlying sequence ( IEnumerable ).
IsNullOrEmpty() Method of C# This method is used when you want to check whether the given string is Empty or have a null value or not? If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings).
Place your cursor on any parameter within the method. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select the option to Add null checks for all parameters.
A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null; otherwise, it returns null . That is, If a evaluates to null , the result of a?. x or a?[x] is null .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With