List New Class takes up memory?
Do I need C=null; in the code below?
//class Category
public List<Category> SelectAll()
{
List<Category> LV = new List<Category>();
string command = "SELECT * from categories";
SqlCommand sc = new SqlCommand(command, new SqlConnection(GlobalFunction.Function.GetConnectionString()));
sc.Connection.Open();
SqlDataReader dr = sc.ExecuteReader();
using(dr)
{
while (dr.Read())
{
// My Question is does this cause a memory problem...
Category C = new Category();
C.CategoryID = Convert.ToInt32(dr["CategoryID"]);
C.Name = dr["Name"].ToString();
C.DisplayOrder=Convert.ToInt32(dr["DisplayOrder"]);
LV.Add(C);
// I was told to add this because if not it would cause a memory leak.
C=Null;
}
}
sc.Connection.Close();
return LV;
}
GridView1.DataSource = List<Category>;
GridView1.AllowPaging = true;
GridView1.PageSize = 5;
GridView1.DataBind();
No, you do not need to explicitly set C to null.
The garbage collector determines if an object can be freed by seeing if there are any outstanding references to the object. As soon as the function SelectAll returns, the only reference to the object should be in LV, from LV.Add(C). The out of scope stack variable will not cause an additional reference, and does not need to be set to null.