Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition if differences in C# and VB

Tags:

c#

vb.net

Why does conditional if in VB require not handle the direct cast of the conditions. For example in C# this is just fine...

        bool i = false;

        i = (1<2)? true:false;

        int x = i? 5:6;

But if I wanted the same thing in VB I would have to cast it

Dim i as Boolean = CBool(IIF(1<2, True, False))
Dim x as Integer = CInt(IIF(i, 5, 6))

I don't understand why C# will do the transform and why VB does not. Should I be casting on my C# conditionals eg

bool i = Convert.ToBoolean((1<2)? True: False);
int x = Convert.ToInt32(i? 5:6);

Also, Yes I am aware that IIF returns type object but I would assume that C# does as well as you can return more than just True|False; it seems to me that C# handles the implicit conversion.

like image 687
Nyra Avatar asked Sep 24 '14 15:09

Nyra


2 Answers

IIf is a function and is not equivalent to C#’s ?:, which is an operator.

The operator version has existed for a while in VB.NET, though, and is just called If:

Dim i As Boolean = If(1 < 2, True, False)

… which is, of course, pointless, and should just be written as:

Dim i As Boolean = 1 < 2

… or, with Option Infer:

Dim i = 1 < 2
like image 160
Ry- Avatar answered Nov 04 '22 08:11

Ry-


This code will show you the difference between the IIf function and the If operator. Because IIf is a function, it has to evaluate all of the parameters to pass into the function.

Sub Main
    dim i as integer
    i = If(True, GetValue(), ThrowException()) 'Sets i = 1. The false part is not evaluated because the condition is True
    i = IIf(True, GetValue(), ThrowException()) 'Throws an exception. The true and false parts are both evaluated before the condition is checked
End Sub

Function GetValue As Integer
    Return 1
End Function

Function ThrowException As Integer
    Throw New Exception
    Return 0
End Function
like image 20
Nick Avatar answered Nov 04 '22 06:11

Nick