Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iif equivalent in C#

Is there an IIf equivalent in C#? Or similar shortcut?

like image 803
Saif Khan Avatar asked May 05 '09 00:05

Saif Khan


People also ask

What is IIf code?

In computing, IIf (an abbreviation for Immediate if) is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter.

What is IIf in VB net?

IIF returns one of two objects, depending on the evaluation of an expression. IIf(Expression As Boolean,TruePart As Object,FalsePart As Object) As Object. IIF is a function and it only specific to VB.NET, because in C# there is no IIF, so it is not the part Common Language Runtime.

What is IIf in Java?

2. 1. JJnguy: No, iif is an inline-if function that takes a boolean value as its first parameter, and when true returns the second parameter, and when false returns the third parameter.


2 Answers

VB.NET:

If(someBool, "true", "false") 

C#

someBool ? "true" : "false"; 
like image 36
Kevin Pang Avatar answered Sep 25 '22 22:09

Kevin Pang


C# has the ? ternary operator, like other C-style languages. However, this is not perfectly equivalent to IIf(); there are two important differences.

To explain the first difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0) 

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:

(true)?1:1/0; 

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. 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 generic IIF(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:

object IIf(bool expression, object truePart, object falsePart)  {return expression?truePart:falsePart;} 

or a generic/type-safe implementation:

T IIf<T>(bool expression, T truePart, T falsePart)  {return expression?truePart:falsePart;} 

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.

like image 81
Joel Coehoorn Avatar answered Sep 25 '22 22:09

Joel Coehoorn