I stumbled onto this awesome operator after a month or 2 of working with C# 2.0 (almost 2 years ago now). Take advantage of it to make your lazy initialization a lot simpler (not worrying about thread safety here). The operator simply returns the left-hand operand if it is not null otherwise it returns the right-hand operand. Take a look at the following progression of the code:
Simple If Statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Further condensed by taking advantage of the ternary operator :
1 2 3 4
Made readable again by taking advantage of the ?? operator:
1 2 3 4
Notice what is happening in that line? If the left hand side of the operand (the activeSession field) evaluates to null, the right-hand operand is returned; which in this case results in an initialization of the field that was null in the first place.Again, this is not new information, I just thought I would throw it out there as a reminder.