It might be basic question, but could anyone explain how does this work. Below code is just example, but in real time this scenario could occur in various places. For ex: While creating DTO for complex object like Customer which has Orders property. Does Orders (=List) need to be instantiated in the constructor of the Customer or just directly assign it to the result of query or a stored procedure.
List<string> list1 = new List<string>()
{
"One", "Two","Three"
};
List<string> list2 = new List<string>();
list2 = list1;
foreach (var s in list2)
Console.WriteLine(s);
List<string> list3 = list1;
if (list3 != null) //is this the only difference
{
foreach (var s in list3)
Console.WriteLine(s);
}
I tried checking the IL code but it wasn’t self explanatory.
IL_0031: stloc.0
IL_0032: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldloc.0
IL_003b: stloc.2
IL_003c: nop
IL_003d: ldloc.1
IL_003e: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
IL_0043: stloc.s CS$5$0000
I am sorry for posting a confusing example. Below is the actual
scenario
DTO:
public class CustomerBO
{
public CustomerBO()
{
Orders = new List<OrderBO>();
}
List<OrderBO>() Orders { get; set;}
//other properties of customer
}
Now in DAL layer:
objCustomer.Orders = Repository.GetAll<OrderBO>("dbo.GetOrdersList");
My question is would it be ok if I initialize Orders object in the CustomerBO constructor (or) skip it and check for null in the presentation layer.
list2: You first create an empty list, then you get rid of it and make list2 point to the same object as list1.
list3: It directly points to the same object as list1.