Is there an IIf equivalent in C#? Or similar shortcut?
Is there an IIf equivalent in C#? Or similar shortcut?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
C# has the
?ternary operator, like other C-style languages. However, this is not perfectly equivalent toIIf(); there are two important differences.To explain the first difference, the false-part argument for this
IIf()call causes aDivideByZeroException, even though the boolean argument isTrue.IIf()is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way,IIf()does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:The other difference is
IIf()is not type safe. It accepts and returns arguments of typeObject. The ternary operator is type safe. It uses type inference to know what types it’s dealing with. Note you can fix this very easily with your own genericIIF(Of T)()implementation, but out of the box that’s not the way it is.If you really want
IIf()in C#, you can have it:or a generic/type-safe implementation:
On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new
If()operator that works like C#’s ternary operator. It uses type inference to know what it’s returning, and it really is an operator rather than a function. This means there’s no issues from pre-evaluating expressions, even though it has function semantics.