0

IIf Function parse both the true part and false part while evaluating the expression.. Am i missing anything? Try this statement and let me know!!

Example:

 Dim sample = ""
 Dim result = IIf(String.IsNullOrWhiteSpace(sample), 0, Integer.Parse(sample))
 Exception = "Input string was not in a correct format."

Fix:

 Dim result = Integer.Parse(IIf(String.IsNullOrWhiteSpace(sample), 0, sample))

http://msdn.microsoft.com/en-us/library/27ydhh0d(v=VS.71).aspx

jeroenh
  • 26,362
  • 10
  • 73
  • 104
Matloob Ali
  • 719
  • 8
  • 9
  • Yes, that is correct. `IIF` is just a function - and functions always evaluate their arguments before executing. The *Remarks/Note* on the MSDN page you linked even says this explicitly. What is your question? – Amadan Jan 03 '12 at 11:39
  • 1
    possible duplicate of [Why won't this work as an IIF function, but will as an IF Statement?](http://stackoverflow.com/questions/3701787/why-wont-this-work-as-an-iif-function-but-will-as-an-if-statement) – Curtis Jan 03 '12 at 11:54

2 Answers2

3

Excerpt from the MSDN document you linked to:

As part of preparing the argument list for the call to IIf, the Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not being called if the other argument is selected by Expression.

This can be rather unexpected behaviour and the design might be flawed, but basically what you assume proves to be correct.

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
3

You are correct in that Iif evaluates all its arguments. It's just a function, so it can't avoid that.

However, VB.net has also had the If operator for a while. It's superficially like Iif, but since it's built into the language, it's not limited the way functions are. It can short-circuit -- only the condition and the correct expression will be evaluated. So, really, it's more like C#'s ?: operator.

result = If(String.IsNullOrWhiteSpace(sample), 0, Integer.ParseInt(sample))

Or, in this case, you may be able to settle for

Dim result as Integer
Integer.TryParse(sample, result)

It'll set result to 0 if it couldn't parse the number.

cHao
  • 84,970
  • 20
  • 145
  • 172