Saturday, September 13, 2008

C# mod operator (%) and negative numbers

The C# mod operator, %, takes the sign of the dividend as the sign of the result. Simply, this means that -1 % 3 is -1, and not 2 as I was expecting. Apparently every language I've ever programmed professionally in behaves the same as C#, so I'm surprised I never noticed it before. Of the other 2 languages I have handy, F# behaves just like C#, while Ruby gives me the result I expected.

A more comprehensive list can be found at Wikipedia.

This came up while trying to learn some WPF. I have a main window and a bunch of child windows that I want to cycle through with ctrl-tab. When I went to add cycling backwards with ctrl-shift-tab I was rewarded with a nice ArgumentOutOfRangeException.