Monday, June 18, 2007

C#: Modulus Operator

Wasn't sure what the modulus operator was in C#. Google came back with this snippet that shows how it can be used to determine even and odd integers:
The code uses C#'s Modulus Operator (%). How this works is the operator computes the remainder after it divides it's first operand by the second. In the case below, the number of controls (i.e. count) is divided by 2. If it's an even-numbered row there won't be a remainder and if it's an odd-numbered row....

if (_pnlMenuItems.Controls.Count % 2 == 0)
{
newMenuItem.BackColor = System.Drawing.Color.LightBlue;
}
else
{
newMenuItem.BackColor = System.Drawing.SystemColors.Window;
}
I just needed to know it's the percent sign; definitely miss the readability of QuickBasic's MOD command. While that snippet is pretty elementary, it's a good example of how to use the modulus.