Home About

November 15th, 2008

Code commenting techniques in C# - 0

When writing new code everything seems so obvious that there is hardly a need to code any comments. But then you get that highly tuned and several times rewritten code library the company has been using for 20+ years. Attached to it is a note asking you to recode it in C# before the weekend.

If you have ever had to work with code left over by other programmers that are no longer around you appreciate the little comments they made on each of their coding decisions. Even your own code, dusted off after some years, can be intimidatingly hard to understand.

Just like C (and C++) C# offers two ways to comment your code: the /* this is a comment */ multi line comment, and the // single line comment.


/* Multi Line Comment Example
   Programmer: Martijn Dijksterhuis
   Date:       November 1, 2008
   Version:    1.0
*/

using System;    // standard IO library
using Gtk;       // We are writing code for Gnome

More important than proper commenting is the need for the code to be self explanatory. Smart and consistent use of variable and function names saves time figuring out what each part does, and reduces opportunity for bugs to creep into your code.

Compare the following two C# implementations of a simple standard mortgage payment calculator:

/* First Implementation */
double P     = 1000.25; 	   // Principal
double Yi    = 0.075;          // Yearly interest
double Y     = 12;             // Years
double mI    = Yi / 12;        // Monthly Interest

// Calculate the monthly payments
double p     = P * mI / (1 - (Math.Pow(1 / (1 + mI), Y * 12)));

/* Second Implementation */
double Principal       = 1000.75;
double YearlyInterest  = 0.075;
double Years           = 12;
double MonthlyInterest = YearlyInterest / 12;
double MonthyPayment   = Principal * MonthlyInterest / ( 1 - Math.Pow(1/(1+MonthlyInterest),Years*12)));

The first implementation requires much documentation in the form of comments to be readable. The second one is self documenting.

Image credit: dalvenjah

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google
  • Reddit

Tags: ,

Leave a Reply


Recent Comments
  • Ales: Hi, Thanks for the code… I must say I did not experience any errors decrypting any of my messages. I even...
  • JC: Thanks very useful and well explained
  • Thomas: This is a public static class written in the C# language that does not save state. You can call into the...
  • Simon: Thank you very much for this post! It helped me essentially to overcome obstacels to work with mono!
  • Graham: This is a good research for keyboard shortcuts! Some shortcuts are also compatible for Windows OS. I have...