C# Code Review

The following is my own personal list of things to avoid in C#. I use this as a guide for my own code reviews. I’ll add points as and when I find them, feel free to make suggestions.

1 General
1.1 Use String.IsNullOrEmpty instead of String == null.
1.2 If a class contains only value types and no methods, consider replacing it with a struct.
1.3 For objects that implement IDisposable, instantiate them inside a ‘using’ block.
1.4 Code to an interface, not a specific class.
1.5 Code should be open to extension, but closed to modification.

2 Naming
2.1 Start the namespace with the company name.
2.2 Do not use hungarian notation for variable names.
2.3 Prefix I to interface names.
2.4 Suffix Exception to exception names.
2.5 Namespace, class and method names should use upper Camel casing.
2.6 Variable names should use lower Camel casing.
2.7 Do not use abbreviations as variable names.
2.8 Prefix boolean variables and properties with ‘Is’.

3 Documentation
3.1 All classes should have a header description.
3.2 Methods should have descriptions, including their variables.
3.3 Use XML tags for documentation.

4 Exceptions
4.1 Don’t create instances of Exception, use a derived Exception.
4.2 Only catch exceptions where you need to take a specific action i.e. Record the error in a log.
4.3 Preserve the stack trace when rethrowing an Exception, use ‘throw;’ instead of ‘throw ex;’.
4.4 Don’t throw Exceptions from static constructors.

5 Program Flow
5.1 Use foreach instead of for.
5.2 Always include the default case in a switch statement.

Advertisements
This entry was posted in Code Reviews and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s