The following works:
If 1=1
rdoYes.checked = True
Else
rdoNo.checked = True
End If
However, the following doesn't work:
IIF(1=1, rdoYes.checked = True, rdoNo.checked = True)
Why is this?
Thanks!
The following works:
If 1=1
rdoYes.checked = True
Else
rdoNo.checked = True
End If
However, the following doesn't work:
IIF(1=1, rdoYes.checked = True, rdoNo.checked = True)
Why is this?
Thanks!
Because IIf
takes expressions and returns a result of one of them, and rdoYes.checked = True
is not an expression and cannot be returned.
The IIF()
function will return something based on what you enter for the first parameter. Since VB.Net doesn't differ between =
as in assignment and =
as in comparison (==
in many other languages), the second statement is ambiguous.
You can do this with using late binding (delegates in VB.Net):
(Function(c) InlineAssignHelper(c.Checked, true)).Invoke(IIf(1 = 1, chkYes, chkNo))
Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
It does "work"; it just doesn't do what you want.
IIf
in VB.NET is a function (don't use it, ever, by the way), which takes these parameters:Boolean
condition to checkObject
to return if the condition isTrue
Object
to return if the condition isFalse
In your usage, your condition is
1 = 1
; then your two other parameters arerdoYes.Checked = True
andrdoNo.Checked = True
, bothBoolean
expressions from the VB compiler's perspective (so, really, they're equivalent to the simplerrdoYes.Checked
andrdoNo.Checked
).Remember that in VB.NET, the
=
sign is only an assignment if it is on its own line. This is how the compiler distinguishes between statements such asx = 5
andIf x = 5 Then
.This is not directly related to your question, but you should also be aware that
IIf
is deprecated and you should almost always favorIf
instead: