March 2006 - Posts

Public readonly string vs. public readonly property

EricGu (Microsoft) has made an excellant post on readonly strings and read-only properties. Check it out

http://blogs.msdn.com/ericgu/archive/2006/03/17/553934.aspx

Posted by Vipul Patel | with no comments

My articles on "Anonymous types" is up

Check out http://www.developer.com/net/csharp/article.php/3589916 for my article on "Anonymous Types", This cool new feature coming in C# 3.0 is surely going to go places.

Codeguru also contains the same article at http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c11551/

Next stop, extension methods.

Posted by Vipul Patel | with no comments

Guidelines on clean up code

Many a times, we use the catch block inside the try catch block for our clean up code.

Something like

try

{

 // Do something

}

catch

{

    // work failed, clean up code here
}

 

Rather than the above approach of using the catch block, it would be nicer to use the finally block, something like

 

bool workSuccessful = false;

try

{

   // do some work

   workSuccessful = true;

}

finally

{

  if(!workSuccessfull)

  {

    // cleanup code here.

  }

}

 

There is elegance in the latter method and I would certainly recommend that approach, if you cannot use "using". See below for details.

 

PS: Use this approach only if better alternatives are not available. One of the automatic cleanup approaches available with C# is the using construct.

Something like,

using (TextReader tr = new StreamReader("FileName"))

{

  // do my work here.

}

 

The “using” construct automatically clean up the unmanaged resource (TextReader) once the block has completed execution.

In the event that you cannot use "using", the try-finally approach would be the best way.

 

Posted by Vipul Patel | with no comments