Letters from Readers
Letters: The Good, Bad and Ugly of C#
Readers respond to C# Corner columnist Patrick Steele's look into the best and worst of the C# programming language.
This is a great compilation. One thing I'll add on the try/catch block -- that I think we as Microsoft developers miss -- is the need to throw the original exception.
Or we need to stuff it in an inner exception and then throw it as a custom exception. Wrapping exceptions preserves the original downstream stack trace and gives the developer the opportunity to throw a meaningful exception -- -perhaps with more information in the form of properties -- beyond something as generic as an argument exception. This by no means is meant to advocate overuse of custom exceptions, but they also have their place and, in my experience, don't get used enough.
Every programming language that gives you a lot of flexibility and power has bad and ugly things. That's not the fault of the language -- it's an inevitability. We learn to avoid doing things in bad and ugly ways.
I'd like to thank Patrick for these timely reminders. I'm going to audit my current project for these issues today. If I may, I'd like to nominate "Bad Grammar and Spelling" to his list of "The Ugly." It's a real pain to try to understand C# code -- or any code -- that has comments and messages that are awkward, too terse or error-riddled. For instance, the first example in "The Bad" should throw a nested BadGrammarException (a recent invention of mine), as a better description for the exception would be "The amount cannot be negative" or "The amount must not be negative."
As developers, we often forget that ordinary people and late-night programmers are trying to use our software. We must make our programs easy to read, especially when errors occur.
As a final example, consider the difference a single comma makes between "Let's eat, Grandpa!" and "Let's eat Grandpa!"
Nice list. But I think properties should have been listed under bad. They're misleading because to the user of a class they look like variables, but they're methods. Getting a variable will not change a class' state, assigning a value to it will only change that specific variable -- and in exactly the way you tell it to. With properties these guarantees are gone -- even getting one could change the state of the class. Awful. Properties should be ditched. Use methods instead.
This story was written or compiled based on feedback from the readers of Visual Studio Magazine.