Does the Dispose () method free memory and make the object null?
Dispose and the delete pattern is not intended to restore managed memory or βdeleteβ managed objects (both things you cannot do and what a garbage collector is), it is designed to handle the removal / release of unmanaged resources or other managed resources that have released items such as SqlConnection . This, of course, will not be a null reference, but may make it unusable from the moment of removal forward.
How can I do this as null or free the memory occupied by this object
If you want to remove the link, just dt = null will work, although this one will not give you any benefit, since the DataTable instance refers to grdView.DataSource . Both dt and grdView.DataSource will be references to the same underlying instance of the DataTable .
I also suspect that this is part of the method, in which case dt in any case be the scope of the method.
You do not need to worry too much about it. I'm more worried about having SqlConnection outside of try-finally / using , you run the risk of leaving an open connection there.
I prefer to call Dispose on elements that implement IDisposable , because I think this is a very good reason: this is a public contract . The fact that calling him does something or not is an implementation detail and may change at the time of notification.
As an aside, I would completely rewrite 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;
source share