Converting VB's IIf to Conditional Operator in c#
-
It's been a while since I've used VB and I need help with understanding the truePart in the second line.
Dim asciiBytes As Byte() = Encoding.ASCII.GetBytes("SomeAsciiData")
Dim nextchar As Integer = IIf(asciiBytes.Length > (i + 1), asciiBytes.Length > (i + 1), -1)
How does
asciiBytes.Length > (i + 1)
return an integer? -
It's been a while since I've used VB and I need help with understanding the truePart in the second line.
Dim asciiBytes As Byte() = Encoding.ASCII.GetBytes("SomeAsciiData")
Dim nextchar As Integer = IIf(asciiBytes.Length > (i + 1), asciiBytes.Length > (i + 1), -1)
How does
asciiBytes.Length > (i + 1)
return an integer?In VB.NET an expression like
asciiBytes.Length > (i + 1)
will return a Boolean value - in this case
True
as it is identical to the Expression part of theIIf
method. Internally, a Boolean value is stored as an integer (False
-> 0,True
-> -1), so the conversion to an integer is straightforward. However, I think there' a bug in your code: it should probably readDim nextchar As Integer = IIf(asciiBytes.Length > (i + 1), asciiBytes(i + 1), -1)
in other words it returns the ASCII value (0 - 255) of the next character in the array if the Expression is
True
and -1 if it isFalse
. -
In VB.NET an expression like
asciiBytes.Length > (i + 1)
will return a Boolean value - in this case
True
as it is identical to the Expression part of theIIf
method. Internally, a Boolean value is stored as an integer (False
-> 0,True
-> -1), so the conversion to an integer is straightforward. However, I think there' a bug in your code: it should probably readDim nextchar As Integer = IIf(asciiBytes.Length > (i + 1), asciiBytes(i + 1), -1)
in other words it returns the ASCII value (0 - 255) of the next character in the array if the Expression is
True
and -1 if it isFalse
.Thanks Geoff I didn't write the code (but that line is working) - maybe the compiler converts the boolean to a 0 or 1 in the background. I'll test it later
-
Thanks Geoff I didn't write the code (but that line is working) - maybe the compiler converts the boolean to a 0 or 1 in the background. I'll test it later
-
Correctly, true equals -1, and 0 equals to false. Perhaps it would be easier to just initialize the variable to -1?
I are Troll :suss:
Absolutely right. :thumbsup: (I incorrectly assumed that true would be 1 and not -1)