Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDE0029 Null check can be simplified C# 6.0 ASP.NET

Tags:

c#

asp.net

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?

like image 565
Liudi Wijaya Avatar asked May 17 '19 10:05

Liudi Wijaya


People also ask

Does any check for NULL C#?

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 ).

How do you handle null values in C sharp?

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).

How do you insert a null check?

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.

What is null conditional operator in C#?

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 .


1 Answers

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.

like image 52
Owen Pauling Avatar answered Sep 18 '22 17:09

Owen Pauling