Considering the follow code can someone explain to me why and why not to use 'using'? I've read about the rule of thumb with IDisposable but why is IDisposable the determining factor?
private string GetWMIProperty(string property)
{
string value = string.Empty;
SelectQuery selectQuery = new SelectQuery("Win32_OperatingSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery))
{
foreach (ManagementObject mo in searcher.Get())
{
value = mo[property].ToString();
}
}
return value;
}
using
translates into try-finally
block. So even in case of exception it will call Dispose
method of the enclosing object.
See: using Statement (C# Reference)
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.