This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: What's wrong with this code?
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
TechEd is rapidly approaching, and I'm signed up to do a “C# Best Practices” kind of talk.
Rather bore my audience by presenting my views on implementing IDisposable, I'm going to take the “What's wrong with this code?” approach. My goal is to present code examples that show code that's doing something wrong - be it something prohibited by the language, something that's ill-advised, or something with bad performance - and then let the attendees try to figure out what's wrong with the code.
I have a list of 10 or 15 items already, but I'd like to steal leverage your experience in this area. If you have a “poor practice”, please post the code, and then leave some blank space before you explain why it's bad, so that others can try to figure them out on their own. I'm especially interested in code that you (or somebody else) wrote where you didn't understand initially what the problem was. In other words, the subtle ones.
Here's one of my favorites. What's wrong with this code?
public class Processor { DataStore dataStore;
public Processor(DataStore dataStore) { dataStore = dataStore; }
public void Process(DiscountStructure discStruct) { try { dataStore.ProcessAllEntries(discStruct); } catch (Exception e) { if (e.InnerException.GetType() == typeof(ProcessFailedException)) { throw new InvalidActionException(e.InnerException); } } } }