C# .NET - what's real advantage of using Interface

Asked By anbu n on 28-Jan-13 06:28 AM
public interface IDisposable
{
void Dispose();
}
 

------------------------------------------
public class MyClass : IDisposable
{
public void Dispose()
{
// Perform any object clean up here.
 
// If you are inheriting from another class that
// also implements IDisposable, don't forget to
// call base.Dispose() as well.
}
}
 
----------------------------------------
 
here in above what's real use of Interface Disposable. why can't the Dispose menmber directly implemented instead
we have to implemenmt Idisposable & then write functionality inside in dispose method.This looks like a long way.
 
First we have to create class then we have to define method name alone & then the class is finally implemneted
& then the fuctionality is to be written in Dispose method. so what's advantage here.
Robbe Morris replied to anbu n on 28-Jan-13 07:57 AM
Implementing the interface in your own class exposes the well known .Dispose method.  The developer using your class then knows to use the "using" clause.  This syntax tells the compiler to convert this whole block to a try/catch/finally which will ensure that .Dispose gets called whether the developer explicitly calls it or now.

Implementing IDisposable is typically done when the class author knows there are resources used in the class that "must" be released as soon as possible upon completion of the work.  So, they put the code to release those resources in a public method called .Dispose.  In the case below, SqlConnection executes .Close and various other things in the .Dispose method.  If you use a tool like Reflector to disassemble the .NET Framework assemblies (they are not obfuscated), you can see what the Microsoft developers have done.

using(var connection = new SqlConnection("blah blah blah"))
{
   // do some stuff

}
anbu n replied to Robbe Morris on 29-Jan-13 12:03 AM
Thanks
tousif khan replied to anbu n on 30-Jan-13 05:22 AM
if you create an interface with one abstract method (by default every method is abstract in interface) every derived class must implement the abstract method. So,every derived class has their own functionality with same method name.