Basic C# coding guidelines

C# 2.0

- 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

List<string> list = new List<string>();

list.Add("aa");

list.Add("bb");

//option 1:

foreach(string str in list)

   Console.WriteLine(str);

//option 2: RECOMMENDED

list.ForEach(delegate(string str) {

 Console.WriteLine(str);

});

- 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)

e.g. instead of the code:

int i;

if(someConditionTrue)

        i = 3;

else

        i = 4;

It is better to write the above 5 lines into just one:

int i = someConditionTrue ? 3 : 4;

- 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 https://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)

Let's say you opened two threads in a web page using the following:

Thread AThread = new Thread(new ThreadStart(CallProcOne));

AThread.Start();

                                   

Thread CThread = new Thread(new ThreadStart(CallProcTwo));

CThread.Start();

//Now it is recommended to do this:

AThread.Join();

CThread.Join();

- 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#

Comments

  • Anonymous
    March 17, 2007
    OK it got off to a slow start, but things started picking up Wednesday morning. I guess the MVP summit