The following doesn’t work:
public string foo()
{
using (Random myRandomChoice = new Random())
{
return myRandomChoice.Next(10).ToString();
}
}
The following is errors:
public string foo()
{
Random myRandomChoice = new Random();
return myRandomChoice.Next(10).ToString();
}
The error message for the first foo is concerning Random not being implicitly convertable to System.IDisposable.
Is this a deliberate ploy withing the syntax of the language so you only use using in specific circumstances e.g when dealing with database connections? or can I explicitly convert Random to type IDisposable so that the initial foo works?
Is there a list available of types that would be better declared with using ?
A
usingstatement is a way to guarantee thatDisposeis called on an object even when an exception is thrown. It is therefore meaningless when the object does not implementIDisposable.The following code examples are equivalent:
(1) A using statement:
(2) Disposing in a
finallyblock:As you can see, all the using statement achieves is disposal of the object, therefore it makes no sense if you object doesn’t implement IDisposable.
FXCop has a rule for checking that you have used
usingstatements for yourIDisposabletypes. See this StackOverflow question for other ways to find which types implementIDisposableand can be used in a using statement.See the MSDN documentation for more information.