Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recognize Disposable Objects in Visual Studio?

It is suggested that IDisposable objects should be disposed in either using statement or by calling Dispose() method. I find it is not intuitive to find out if an object is disposable in Visual Studio.

My question is: is there any way to recognize IDisposable objects in VS?

like image 362
T D Nguyen Avatar asked Apr 26 '17 13:04

T D Nguyen


People also ask

How do you find Undisposed objects in C#?

The simplest way to find undisposed objects is to add some logging to the finalizer of each disposable type. Running the application through typical scenarios and checking the logs should tell you which types are not being disposed.

Is dispose called automatically C#?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.

How use Dispose method in C#?

The Dispose() methodThe Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object. Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. If the type has no finalizer, the call to GC.

What is IDisposable object in C#?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.


1 Answers

If you want to highlight disposable objects differently in VS please check out this post. I personally prefer Resharper answer as I always use R#.

If you just want to figure out if your object is an instance of some interface you can right-button-click on the variable name and Navigate -> Object Browser or Go to Declaration and then right-button-click on class name Go to Definition/Peek Definition.

enter image description here

You might like Peek Definition as it shows everything you need inline:

enter image description here

You can always check what methods object has, if it has Dispose() method then 99.9% it's a disposable object. I'll give this 0.01% for those who give methods bad names :).

like image 117
Andrei Avatar answered Sep 21 '22 18:09

Andrei