Tuesday, August 26, 2014

C# generation: from '?' via '??' to '???'

C# include several usable but not famous operators. Today we'll consider the generation of  operator '?'.
The first and known from language C old operator '?' was appeared in C# 1.0 in the Visual Studio 2002. An operator using for condition instead to block  if-else:
  1. Random rnd = new Random();
  2. //Long way
  3. bool isLessTo50;
  4. if (rnd.Next(100) < 50)
  5. {
  6.    isLessTo50 = true;
  7. }
  8. else
  9. {
  10.    isLessTo50 = false;
  11. }
  12.  
  13. //Short way
  14. bool isLessTo50 = rnd.Next(100) < 50 ? true : false;

The next '??' was offered 3 years later in Visual Studio 2005. The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand:
  1. DateTime? dt = GetDate();
  2. //Regular way
  3. if (dt != null)
  4. {
  5.    return dt;
  6. }
  7. else
  8. {
  9.    return DateTime.Now;
  10. }

  11. //Short way
  12. return (dt != null) ? dt : DateTime.Now;

  13. //New way
  14. return dt ?? DateTime.Now;

The last operator '???' was announced in Visual Studio 2012. I'm very like it because he is cutting the validation of object:
  1. class Person
  2. {
  3.  public string Name { get; set; }
  4.  public int ID { get; set; }
  5. }
  6.  
  7. //The program
  8.  Person person = InitPerson();

  9. //Old way
  10. if (person != null)
  11. {
  12.   return person.ID;
  13. }
  14. else
  15. {
  16.   return default(int);
  17. }
  18.  
  19. //New way
  20. return person.ID ??? default(int);

In Visual Studio 2014 the operator '?..' did not receive renewal but maybe in next versions we'll see '????'  and even '?????' :-).