Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Try - finally alternative

5.00/5 (5 votes)
5 Jun 2011CPOL 8.8K  
Not really, because what if your finally block would contain more lines of code than the single line you have in your example? That would make it already much harder to read.Secondly, you are misusing the Dispose method. You shouldn't invoke anything in it, especially not the Action, you...

Not really, because what if your finally block would contain more lines of code than the single line you have in your example? That would make it already much harder to read.


Secondly, you are misusing the Dispose method. You shouldn't invoke anything in it, especially not the Action, you should only be disposing used objects in it.


Also, where is the catch? When you are defining a try-block, you will need a catch in a proper design.


So in my opinion, this stays better:


C#
try 
{
}
catch(Exception ex) 
{
}
finally 
{
}

You could make it a Fluent interface like this:


C#
Try( () => Console.WriteLine("test") ).Catch((Exception ex) => 
    Console.WriteLine(ex.Message)).Finally(() => Console.WriteLine("Done!"));

But I don't think that's more readable either..

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)