Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# null check can be simplified

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.
 
PREVIOUS NEXT
Tagged: #null #check #simplified
ADD COMMENT
Topic
Name
1+4 =