Oct 09

While I was catching up on my blog roll, I’ve noticed that my friend Alberto ended up being surprised by another nitpick difference between C# and VB.NET which does not help the programmer which needs to be proficient in both languages. Here’s the culprit code (in VB.NET and then in C#):

Dim x as Integer = 5 / 20 * 100

int x = 5 / 20 * 100;

At first, they do look the same, don’t they? But nop, they’re not the same. Unfortunately, VB.NET has 2 operators for division: / and \. In practice, / will run the division and return a float (don’t ask me why!), while \ returns the integer result (discarding the remainder).

Now, I really don’t want to start bad mouthing VB.NET, but in this case, we’re dividing two integers, so I’d expect to get an integer. Now, this probably won’t make sense to the long time VB.NET programmer, but the truth is that C# will only allow you to perform three “division types”: integer, floating point and decimal.

I really don’t agree with my friend Alberto, which classifies C#’s behavior as wrong. In fact, I think it’s correct and it does help to achieve type safety. but hey, that’s me, a C# lover (and also a VB.NET critic Smile)

2 comments so far

  1. Jonathan Allen
    1:38 am - 10-10-2012

    It is the same as == vs is/= or + vs &. VB requires you to specify what you want, C# overloads the operator to do two unrelated things.

    This may not seem too important now, but if you are working with dynamically typed data then the difference between floating point and integer division becomes really important, as does the difference between value and reference equality or addition vs concatenation.

  2. luisabreu
    11:29 am - 10-11-2012

    but you don’t need to work with dynamically typed data to see that there’s an important difference between types. Btw, the framework does give you the tools to be explicit about what you want, so you really don’t need to resort to the operators if you don’t like the way they work (btw, I don’t agree regarding the == operator. IMO, it does work correctly for most of the CLR predefined types).