While reading some blogs today, I ran across a nice C# coding standards document. The document closely follows Microsoft's “Design Guidelines for Class Library Developers” and is very similar to my personal standards. My notes, as well as some additional standards I try to follow, are below:
I prefer to prefix private fields with an underscore.
Not necessary. The runtime knows when objects are no longer used, even within the body of a method. For example:
1 MyObject o = new MyObject();
If a GC occurs at line three, the object referenced by "o" may be garbage collected.
Classes with internal accessibility don't need to follow this, as versioning is not an issue. All consumers of objects of that type are compiled with the class.
I prefer to have all of the fields at the top of a class in order of accessibility from public to private.
- For methods that return arrays, always return an array. If the method produces no results, return an empty array instead of null. If you must return null, note this in the XML documentation.
- Use explicit interface implementation for code that does not adhere to the roll of the object, ie. debug code. For example, sometimes it's helpful while debugging to get a certain value from each object in a custom collection. A GetProductIDs method can be written to obtain these values, but the method has no practical use to the consumer and, since it's debug code, it may be changed or removed in the future. It also pollutes the public interface. Classes that contain methods like these should implement an I
- Provide as much information as possible in exceptions, including how to possibly avoid the exception in the future. Provide state information, if possible. For example, if a ProcessInvoice method encounters a line item without an ID, include the name of the product in the error message or in a property off of the custom exception. This can make debugging much easier for the consumer.
- Never store the integral value of an enum between application sessions. Members of the enum may be removed or reordered.