Thursday, January 22, 2009

Visual C# Ternary operation

Right from my days of C++, this ternary operation has always confused me, primarily because I never spent enough time to understand this operation. Now that I have, I am documenting it here so that this can be referred back in future if needed, or for others like me.

The only ternary operation in C# is the comparison operation which has the following syntax:

<test>?<resultIfTrue> : <resultIfFalse>

Example:

string resultString = (myInt<10) ? "Yep!!!!" : "Nope!!!"

Here, the resultString variable will hold the string "Yep" if the variable myInt has a value less than 10. Otherwise, if the value held by myInt is greater than or equal to 10, the variable resultString will hold a value "Nope!!!".

No comments: