简体   繁体   中英

Does C#/VB.NET using statement actually do anything with classes that do not implement IDisposable

If i have something like the following:

public class Myclass{

//some resources

}

and then in another class i do the following:

using(Myclass myclass = new Myclass()) {
// do things with myclass instance

}

Does the using statement in this case actually provide any use? Myclass has not implemented the IDisposable interface so there isn't any Dispose() method to call. Am i thinking about this correctly?

If your class is not implementing IDisposable then you can't use it inside using statement. It would be a compile time error.

Other than that, using statement translates into try-finally block and at the end of using statement, Dispose is called (even in case of an exception) . There is nothing magical done by CLR to actually dispose the object, it all depends on the implementation of Dispose . You can have an empty implementation of Dispose method and there will be no effect.

You cannot use using with types that don't implement IDisposable . You will get a compiler error. That's it.

  • MSDN C# : ... All such types must implement the IDisposable interface....
  • MSDN VB.NET ...Required. The class of the resource. The class must implement the IDisposable interface...

This is the CS1674 compiler error you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM