CodeSOD: The Wrong Kind of Character

This post was originally published on this site

The Daily WTF

Today’s code, at first, just looks like using literals instead of constants. Austin sends us this C#, from an older Windows Forms application:

if (e.KeyChar == (char)4) { // is it a ^D? e.Handled = true; DoStuff(); } else if (e.KeyChar == (char)7) { // is it a ^g? e.Handled = true; DoOtherStuff(); } else if (e.KeyChar == (char)Keys.Home) { e.Handled = true; SpecialGoToStart(); } else if (e.KeyChar == (char)Keys.End) { e.Handled = true; SpecialGoToEnd(); }

Austin discovered this code when looking for a bug where some keyboard shortcuts didn’t work. He made some incorrect assumptions about the code- first, that they were checking for a KeyDown or KeyUp event, a pretty normal way to check for keyboard shortcuts. Under that assumption, a developer would compare the KeyEventArgs.KeyCode property against an enum- something like e.KeyCode == Keys.D && Keys.Control, for a CTRL+D. That’s clearly not what’s happening here.

No,

To read the full article click on the 'post' link at the top.