I am trying to understand using block in C#. Can I create a custom object inside Using statement like the below which doesn't implement the IDisposable interface?
Class A
{
}
using(A a = new A())
{
}
It gives me error saying "Error 1 'ConsoleApplication1.A': type used in a using statement must be implicitly convertible to 'System.IDisposable'"
How to correct this error? I do not want to do Class A : IDisposable
Any other way? Or it is a mandatory requirement that we need to implement IDisposable Dispose method in these kind of custom objects which we use inside using block?
EDIT: I am NOT expecting the definition that is there in the MSDN and thousands of websites. I am just trying to understand this error and also the rectification
Using blocks are syntactic sugar and only work for IDisposable objects.
The following using statement:
using (A a = new A()) {
// do stuff
}
is syntactic sugar for:
A a = null;
try {
a = new A();
// do stuff
}
finally {
if (!Object.ReferenceEquals(null, a))
a.Dispose();
}
The whole point of using is to create the equivalent of a try block with a call to Dispose in finally. If there is no Dispose method, there is no point to the using statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With