Monday, January 14, 2008

C# ternary if

Just to get some exposure for pretty specific searches, I wanted to give some examples of the ternary "if" statement in C#: If you would like to set a variable by an "if...else" condition, it can be done with the ternary if statement. (Notice I am also using the new .NET 3.5 "var" to declare my variable). In the example below, I want to see if I am old enough (25 yrs old) to rent a car without the "underage" fee. Is today 25 years or more from my date of birth:
DateTime myBDay = "02/08/1982";
var AmIOldEnough = DateTime.Today >= myBDay.AddYears(25) ? true : false;

1 comment:

rtpHarry said...

well it worked, you are top search result for c# ternary