4

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

2
  • Could you elaborate on why you don't want to use IDisposable? Maybe something better could be found. Commented Dec 5, 2013 at 6:19
  • @antiduh: Well let me rephrase my words for you. What is the meaning of that error "Convertible" Commented Dec 5, 2013 at 7:43

2 Answers 2

12

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();
}
Sign up to request clarification or add additional context in comments.

7 Comments

Why 2 calls to new A?
You should just leave a = new A(); since variable a already exists
whoops, you are right.. and it seems to have been fixed up by some editors (thank you!)
@syazdani: This I know 3 years back and my question is not that. My question is completely different from what you have understood
All "implied convertible" means is that the runtime should be able to cast a given object to a given type and get a meaningful result (in this case, casting A to IDisposable). In some situations, the compiler can check for this during compile time and give you an error if it is not possible (as it is doing for you because A does not implement IDisposable). Read more here: en.wikipedia.org/wiki/Type_conversion
|
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.