I need to force the use of \"using\" to dispose a new instance of a class.
public class MyClass : IDisposable
{
...
}
using(MyClass obj = new MyClass())
It's ugly, but you could do something like this:
public sealed class DisposableClass : IDisposable
{
private DisposableClass()
{
}
public void Dispose()
{
//Dispose...
}
public static void DoSomething(Action<DisposableClass> doSomething)
{
using (var disposable = new DisposableClass())
{
doSomething(disposable);
}
}
}
No, you cannot do that. You can't even force them to call dispose. The best you can do is add a finalizer. Just keep in mind that the finalizer will get called when the object is disposed and that is up to the runtime.
I wonder if FXCop could enforce that rule?
The using statement is a shorthand that the compiler converts from:
(using DisposableObject d = new DisposableObject()){}
into:
DisposableObject d = new DisposableObject()
try
{
}
finally
{
if(d != null) d.Dispose();
}
so you are more or less asking if it is possible to enforce writing a try/finally block that calls Dispose for an object.