Using statement in C# without implementing Dispose Method
.net, c#, c#-4.0, using
Solution
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();
}
Problem
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