// 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;
//Return stirng representation of nullable DateTime
DateTime? x = null;
return x.HasValue == true ? x.Value.ToString() : "No Date";
// Prior to C# 6
var title = null;
if (post != null)
title = post.Title;
// c#6
var title = post?.Title;
// Prior to C# 6
var count = 0;
if (post != null)
{
if (posts.Tags != null)
{
count = post.Tags.Count;
}
}
// C# 6
var count = post?.Tags?.Count;
// Null-conditional operators ?. and ?[]
// Available in C# 6 and later: basically means:
Evaluate the first operand; if that's null, stop, with a result of null.
Otherwise, evaluate the second operand (as a member access of the first operand)."
//example:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Name == null
{ mapped.Name = "N/A"}
else { mapped.Name = Model.Model2.Model3.Name; }}
// can be simplified to
mapped.Name = Model.Model2?.Model3?.Name ?? "N/A";