Does Dispose() method does not free up the memory & make object as
null ??
Dispose
and the disposal pattern is not for reclaiming managed memory or "deleting" managed objects (both things you cannot do and what the Garbage Collector is there for), it is for handling the disposal/release of unmanaged resources or other managed resources that have releasable items, such as SqlConnection
. It certainly won't null
the reference, but may make it unusable from the time of disposal forwards.
How can i make it as null or free up the memory occupied by this
object ??
If you want to null the reference, simply dt = null
will work, though this will not give you any benefit as the DataTable
instance is referenced by grdView.DataSource
. Both dt
and grdView.DataSource
will be references to the same underlying DataTable
instance.
I also suspect this is part of a method in which case dt
is method-scoped anyway.
You shouldn't have to worry too much about any of this stuff. I'd be more concerned about having the SqlConnection
outside of a try-finally
/ using
, you are at risk of leaving a connection open there.
I tend to favour calling Dispose
on items that implement IDisposable
for what I think is a very good reason: this is the public contract. The fact of whether calling it does anything or not is an implementation detail and is liable to change at a moments notice.
As an aside, I would completely re-write your code:
var dt = new Datatable();
using (var conn = new SqlConnection(""))
using (var comm = new SqlCommand("sp_getData", conn))
{
conn.Open();
using (var reader = comm.ExecuteReader())
{
dt.Load(reader);
}
}
grdView.DataSource = dt;