There are several ways to comment your code. There’s the style where you place comments on the same line as the code. This might get less readable, because there’s some horizontal scrolling involved when your statements get longer. An example:
string s; //Declare string
s = e.Message; //Assign exception message to string s
Another way to place comments in your code is to place every comment on its own line. This is less readable when you get long methods, because your methods will get twice as long because of the comments! An example:
//Declare string
string s;
//Assign exception message to string s
s = e.Message;
My thoughts about commenting are: don’t. I think naming should be so readable that every line of code makes sense. Use the C# ‘three-slashes-comment-block’ to explain what a method does which parameters it takes and, if necessary, what it returns. The above given code example would look like this:
string exceptionMessage;
exceptionMessage = exception.Message;
This piece of code doesn’t really move mountains, so it’s kind of hard to find a good descriptive piece of text for it. I’ll leave that up to your own imagination ;).
You see that, by naming the Exception ‘exception’ in stead of ‘e’, it is instantly much clearer what it contains. The string is now called ‘exceptionMessage’ which leaves very little place for argument as to what this variable would contain. Therefore the line where the exception message is assigned to the string doesn’t need any comments. This eliminates all comment within your code, except for maybe the occasional exotic function you call, where you need to specify why or how you’re calling it…
I agree with Gerke’s observation about code needing refactoring instead of comments. In the coding guidelines for the .NET team at the customer I work for, I have included the "rule" that methods should not contain more than 5-10 lines (not counting whitespace, comment lines and lines with just { or }). Short methods are less complex, thus easier to understand without needing comments and can be tested better than complex methods.
There is a more scientific way of expressing this: there is a number called the cyclomatic complexity of a method. Roughly it’s the number of possible flows through your method. Every if statement, loop etc. increases the cyclomatic complexity. This number should be low. For more details see http://www.visibleprogress.com/vb_cyclomatic_complexity_metrics.htm.
The VS add-in C# Refactory can calculate the cyclomatic complexity for every method for you and show other metrics about a project as well. Check out http://www.xtreme-simplicity.net/CSharpRefactory.htm
Unfortunately, when I do code reviews (without C# Refactory because the client has no licenses) I see that my team members like writing methods with high cyclomatic complexity and ignore the guideline on minimizing this ;(