Search
 
SCRIPT & CODE EXAMPLE
 

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

PREVIOUS NEXT
Code Example
Csharp :: unity how to ommit letters from a string 
Csharp :: C# inline question mark on object 
Csharp :: which gas is at anode 
Csharp :: how to get the color of other label when clicking c# 
Csharp :: c# datatable copy selected rows to another table 
Csharp :: c# unity camera follow 
Csharp :: how to unfreeze a rotation in a collider unity 2d 
Csharp :: how to make a object disapear in windows form c# 
Csharp :: stop sound in unity 
Csharp :: play sound unity 
Csharp :: c# set int infinity 
Csharp :: mvc input type file 
Csharp :: use only one class from a namespace in c# 
Csharp :: ++ operator c# 
Csharp :: save file dialog filter c# 
Csharp :: change array size in unity 
Csharp :: assign long value c# 
Csharp :: c# sort array string by length 
Csharp :: c sharp if string equals 
Csharp :: c# get pixel color from image 
Csharp :: c# check if array is empty 
Csharp :: How can you learn C# on your own 
Csharp :: c# dictionary first 
Csharp :: unity controls 3d 
Csharp :: select a object from list based on a value csharp 
Csharp :: varibles c# 
Csharp :: c# array of strings 
Csharp :: c# parse the date in DD/MMM/YYYY format 
Csharp :: how to find a gameobject in unity 
Csharp :: linq distinct count 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =