C# and question marks

One cool operators that C# offers us is ?? But before ?? we should know what does ? after variable type name. So, let's take both of these question marks and let's see what they are. Also let's jump for a while behind compilator to see IL code that compiler produces.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

4 Comments

  • While ur at it I would have added the ternary operator:

    bool isOdd = (1 == i % 2) ? true : false;

    nullable types, null coalescing are more related, but the article title is "... question marks". Ternary opertator is overlooked a lot and it can be "nested" to do more complex operations.

  • Bart - except in your example you don't need the ternary operator.

    bool isOdd = (1 == i%2);

    That obviously suffices.

    Agreed though, that it is overlooked a lot, and it's a pain in the eye (use 3-letter word of your choosing) to see code like:

    if (something.Valid())
    return true;
    else
    return false;

    Yuck!

  • Actually, the best place for a ternary is where an if() would be completely wrong:

    Console.WriteLine("Your answer was {0}. This {1} correct", myAnswer, isCorrect(myAnswer) ? "IS" : "is NOT");

  • Thanks a lot for this little article :)
    I can understand better the code I'm reading now

Comments have been disabled for this content.