Click here to Skip to main content
15,904,416 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi


How to dispose the interface objects in C#?




Thanks in advance.
Posted
Comments
OriginalGriff 17-Feb-11 5:25am    
That isn't too clear - please edit your question and describe what you are trying to achieve.
Do you mean User Interface objects like TextBoxes?
Or what do you mean?

1 solution

An interface is just defines a contract.

From MSDN: "13. Interfaces
Visual Studio .NET 2003

An interface defines a contract. A class or struct that implements an interface must adhere to its contract. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

Interfaces can contain methods, properties, events, and indexers. The interface itself does not provide implementations for the members that it defines. The interface merely specifies the members that must be supplied by classes or structs that implement the interface."


So, you don't dispose of Interfaces per se, you dispose of the objects that implement them. You could have an object that looks like this

public class SomeDisposableObject : IMyCustomInterface, IDisposable
{
   // Implementation of IMyCustomInterface and IDisposable in here!
}


Now you could have a method that gets this reference as follows

IMyCustomInterface foo = new SomeDisposableObject ();
foo.Whatever();
((IDisposable)foo).Dispose();


That's not very clean though, it would be nicer if we could just use a using block around the interface. In which case, have your interface inherit IDisposable

public Interface IMyCustomInterface : IDisposable
{
    void Whatever;
}


You can now use like

C#
using (IMyCustomInterface bar = new SomeDisposableObject())
{
    bar.Whatever();
}
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 17-Feb-11 5:49am    
Good answer! 5+
Putting quotes around what you copied from MSDN is a good start. When I do this I also add italic <i> tag so it's easier to distinguish from my own content.
See my edit and keep it if you like it better that way.
Dylan Morley 17-Feb-11 5:51am    
yep, that works - cheers

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900