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:
- Random rnd = new Random();
- //Long way
- bool isLessTo50;
- if (rnd.Next(100) < 50)
- {
- isLessTo50 = true;
- }
- else
- {
- isLessTo50 = false;
- }
- //Short way
- 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:
- DateTime? dt = GetDate();
- //Regular way
- if (dt != null)
- {
- return dt;
- }
- else
- {
- return DateTime.Now;
- }
- //Short way
- return (dt != null) ? dt : DateTime.Now;
- //New way
- 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:
- class Person
- {
- public string Name { get; set; }
- public int ID { get; set; }
- }
- //The program
- Person person = InitPerson();
- //Old way
- if (person != null)
- {
- return person.ID;
- }
- else
- {
- return default(int);
- }
- //New way
- 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 '?????' :-).