tags:

views:

55

answers:

1

whatd does following code do in VB?

Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(0), 16) Mod 2) = 1

note :Private rmaValidationCode As String

+2  A: 

This is actually slightly tricksy:

Let's pick it apart:

rmaValidationCode.ToCharArray().GetValue(0)

gets the first character in the string. Replacing that expression with c for simplicity:

Convert.ToInt32(c, 16)

is interesting... because there's no overload to Convert.ToInt32(char, int). Instead, the VB compiler inserts an implicit conversion from Char to String and then calls Convert.ToInt32(string, int). In this case it's parsing it as hex. So we've got "parse the first character of the string as a hex digit (after converting that first character back to a string)". Now let's substitute that expression with x:

(x Mod 2) = 1

that just takes the remainder after dividing by 2 and tests for it being 1.

So overall, this code tests whether the first character in the string is 1, 3, 5, 7, 9, B, D or F (case-insensitively). If so, the result is true. If the first character is 0, 2, 4, 6, 8, A, C, or E, the result is false. If the string is null, empty or the first character is none of the ones listed, an exception will be thrown.

Jon Skeet
thanks for replying.Does x contains hex equilvalent of c?for example if c= 10 then Convert.ToInt32(c, 16) will return A??
No, that's the wrong way round. `x` is an integer. `c` is a character. So if `c='A'` then `x=10`.
Jon Skeet
If `c` is Unicode character 10 (i.e. a newline character) then `Convert.ToInt32(c, 16)` will throw an exception.
Jon Skeet