? ??

Nullable value types are often required when working with event handlers that use the vanilla object class for parameter passing. e.g.

private void EventHandler(object dateTime)
{  
  DateTime? date_time_nullable = dateTime as DateTime?;
  DateTime date_time;
  if (date_time_nullable.HasValue)
  {
    // Use the value.
    date_time = date_time_nullable.Value;
  }
  else
  {
    // Set a sensible default value
    date_time = DateTime.Today;
  }

  // Do something with the date_time
}

This is quite a long winded process for determining the parameter that was passed into the function. There’s got to be a better way… and there is!

With the help of “? ??”, the above code can be written cleanly in one line.

private void EventHandler(object dateTime)
{  
  DateTime date_time = dateTime as DateTime? ?? DateTime.Today;

  // Do something with the date_time
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>