carlAlex
8/24/2016 - 10:56 AM

C# null-conditional operator

C# null-conditional operator

var handler = this.PropertyChanged;
if (handler != null)
    handler(…)
int? length = customers?.Length; // null if customers is null 
Customer first = customers?[0];  // null if customers is null
int? count = customers?[0]?.Orders?.Count();  // null if customers, the first customer, or Orders is null
PropertyChanged?.Invoke(e)
public static string Truncate(string value, int length)
{          
  return value?.Substring(0, Math.Min(value.Length, length));
}
public static string Truncate(string value, int length)
{
  string result = value;
  if (value != null) // Skip empty string check for elucidation
  {
    result = value.Substring(0, Math.Min(value.Length, length));
  }
  return result;
}