selvaraj
selvaraj

Reputation: 899

What is meant by connection.Dispose() in C#?

What is meant by connection.Dispose() in C#?

Upvotes: 7

Views: 6225

Answers (4)

Cheng Chen
Cheng Chen

Reputation: 43523

A class implements IDisposable interface contains a method called Dispose(), where you can release resources or do something else.

Also, a using statement can help to call Dispose() method automatically.

using (SqlConnection connection  = new SqlConnection(connStr))
{
   //do something
}// it will automatically Dispose() here

What happens when you call myClass.Dispose() depends on what you wrote in the Dispose method. For example:

public class MyClass : IDisposable
{
   //since MyClass implements IDisposable, it must contain a Dispose() method otherwise will compile error
   public void Dispose()
   {
      // do something
   }
}

so if you want to know what happened when you call connection.Dispose(), you must take a look at the Dispose() method of the class of connection(maybe it's a SqlConnection?). If it's a .NET built-in library(which means you can't get the source code easily), you can use a tool to help called Reflector

Upvotes: 7

PrateekSaluja
PrateekSaluja

Reputation: 14936

Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

Example:-

void DataTest()
{
 using(SqlConnection conn1 = new SqlConnection(...)) {
  conn1.Open();
  SqlCommand mycommand = new SqlCommand("Select * From someTable", conn1);
  using(SqlDataReader myreader = mycommand.ExecuteReader()) {
   if(myreader != null)
    while(myreader.Read())
     Console.WriteLine(myreader.GetValue(0).ToString() + ":" + myreader.GetTypeName(0));

  }
  mycommand.Dispose(); 
 }
}

Upvotes: 9

Du Jianyu
Du Jianyu

Reputation: 63

the conn.Dispose() is call the function in unmanage code.

in fact when programming,you needn't to call this function,just call the conn.Close();

Upvotes: 0

Rohan West
Rohan West

Reputation: 9298

Generally Dispose is called to free resources when you are finished using the component.

The Dispose method on a SqlClientConnection object will force the connection to close.

It is a common pattern that can be found not just in .Net but Java too.

MSDN should provide all the documentation you need on the correct way to call Dispose

Upvotes: 1

Related Questions