After going through a lot of articles of Idisposable i got confused about it usage. All articles explain what is it and how to implement. I want to understand what we will miss if we don't have it. It is an interface with one method Dispose() in it. Let's take an example Often the use of dispose is shown as disposing a database connection.
The code would be like
Public class Test:Idisposable
{
public Test()
{
DatabaseConnection databaseConnection = new DatabaseConnection();
}
public void Dispose()
{
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
}
}
Although dispose is implemented but inside dispose method the dispose property of databaseconnection is used to free the connection(this.databaseConnection.Dispose();)
My question is why do we need to implement IDisposable in this case? We can directly call this.databaseConnection.Dispose() and free the connection. Why to implement dispose when internally also it calls the dispose property of the object. Alternative to the approach of Idisposable we can implement a method Release to free the memory.
Public Class Test
{
public Test()
{
DatabaseConnection databaseConnection = new DatabaseConnection();
}
public void Release()
{
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
}
}
What is the difference in the two approaches? Do we really need Idisposable? I am looking forward for a concrete explanation.