Thursday, March 15, 2007

Basic C# coding guidelines

Basic C# coding guidelines (from http://blogs.msdn.com/samar/archive/2007/03/15/basic-c-coding-guidelines.aspx) All of the following are good recommendations. The one thing that I dont understand is the one about looping through generic collections using a "anonymous method predicate" - thats one I havent found any information about on the internet. So if you do, please leave a comment.
  • Please do NOT use + sign to concatenate strings, because it creates three instances of string (try doing that in a long or infinite loop, your program will die with OutOfMemory exception in no time), Rather use string.Concat it keeps one instance (and hey no OOM). If concatenating many strings in a loop etc, then use StringBuilder. Alternative to string.Concat is string.Format (which uses StringBuilder inside)
  • Use generic collections instead of Hashtables and ArrayList types
  • If using Generic types, then refrain from using foreach loop on the collection. Rather use ForEach method to loop through via an anonymous method predicate (much faster because doesn’t create the Iterator). For non generic types try to use for loop instead of foreach if the data being traversed is huge
  • Nullify unused objects (doesn’t collect, but marks for collection and ceases from getting promoted into next generation)
  • IF conditions having just one item in if and else, should be used as ternary operator (? Sign)
  • Use ‘as’ operator instead of direct typecast using parenthesis with the exception of overloaded explicit cast operator, it saves from NullReferenceException and InvalidCastException
  • Refrain from XmlDocument usage for navigational purpose, please either use XmlTextReader for sequential access or XPathDocument for XPath based data retrieval
  • For server side XSL transformation, Use XslCompiledTransform instead of XslTransform (Please check http://blogs.msdn.com/antosha/archive/2006/07/24/677560.aspx ). For client side transformation, try to load Xsl file asynchronously whenever possible via XMLDOM or XsltProcessor (Geckos)
  • Always join your threads in a web page, if used (otherwise the page will be rendered and workers will continue operating at the server cost, and ofcourse the results will be unpredictable)
  • Always do NULL checking before operating on an object, NullReferenceException is widely occurring exception in most applications and only a preventive programming can help us get the real error
  • Handle most specific (expected) exceptions in the catch blocks before deciding towards general Exception, and please don’t use catch without an exception object if you’re not really writing P/Invoke in C#

No comments: