difference between List<T> and List<T>=new List<T> in c# -
i sorry if question silly, new c#
i want know exact difference between when create list variable this
list<t> lststudents;
and when create list this
list<t>= new list<t>();
i found out if create variable without intializing object it, still able add new objects, if difference between 2 let me explain scenario code trying
list<product> product = new list<product> { new product() { productid = 1, productname = "a" } , new product() { productid = 2, productname = "b" } , new product() { productid = 3, productname = "c" } , new product() { productid = 4, productname = "d" } , new product() { productid = 5, productname = "e" } };
now if add variable this
list<product> p = product;
i still able add objects in variable
p.add(new product { productid = 3 });
please clarify doubt.
thank
i sorry may doing wrong in code
public class students { public string name { get; set; } public int studentid { get; set; } } list<product> product = new list<product> { new product() { productid = 1, productname = "a" } , new product() { productid = 2, productname = "b" } , new product() { productid = 3, productname = "c" } , new product() { productid = 4, productname = "d" } , new product() { productid = 5, productname = "e" } }; list<product> p = product; p.add(new product { productid = 3 });
when run 6 items instead of 5
now if add variable this
list<product> p = product;
i still able add objects in variable
yes, because the variables referencing same list. if @ p
notice added item reflected there well.
i found out if create variable without intializing object it, still able add new objects
not true - if this:
list<t> lststudents;
and try add something:
lststudents.add(...);
you compiler error if list declaration within method, , nullreferenceexception
if class member because lststudents
not referencing (it "null" reference).
when run 6 items instead of 5
yes because list referenced product
contained 5 elements, p
references same list, , added one.
lists reference types, meaning "copying" value of 1 variable variable copies reference underlying object. it's akin pointers in older languages c.