Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using statement in C# without implementing Dispose Method

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

like image 683
Jasmine Avatar asked Dec 04 '22 08:12

Jasmine


2 Answers

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();
}
like image 84
syazdani Avatar answered Dec 23 '22 08:12

syazdani


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.

like image 29
Jonas Høgh Avatar answered Dec 23 '22 08:12

Jonas Høgh