check for null c# inline code example

Example 1: null coalescing operator c#

//the null coalescing operator for c# is ??
int? x = null;
int y = 9;
return x ?? y; 
//Will return the value of x if x is not null else return y

Example 2: c# null conditional

//Return stirng representation of nullable DateTime
DateTime? x = null;
return x.HasValue == true ? x.Value.ToString() : "No Date";

Example 3: c# null conditional operator if statement

// This is used if the source of a value is uncertain to exist

// For both of these examples, if 'p' is null, 'name' and 'age' will be null
// (as opposed to throwing an error)
string name = p?.FirstName;
string age = p?.Age;

string silver = preciousMetals?[4]?.Name;

Example 4: c# null accessor

int? length = people?.Length; // null if people is null