Tuesday, August 24, 2010

Is it better to use the [using] directive in C# or the [dispose] method? Does this apply to external (COM) objects?

Programmer Question

I've seen this be a lively debate between the Microsoft C# folks and Microsoft Exchange CDO support groups.



What is better, the using directive, or the dispose directive when finished with an object?



 using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}


On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.



Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails