I have a function which goes like this
public class Component
{
public List<SubComponent1> subComponent1 {get;set;}
public List<SubComponent2> subComponent2 {get;set;}
}
public void Update()
{
List<Component> collection = new List<Component> collection();
//populate from service
collection = getData();
//I want to update subComponent1
List<SubComponent1> copycomp = null;
copycomp = collection.subComponent1;
UpdateService1Data(ref copycomp);
}
public void UpdateService1Data(ref List<SubComponent1> subcopy)
{
//Do some operations and update SubComponent1
//Changes will reflect in collection object
}
My question goes like this:
In the Update()
function copycomp
is referring to the object within collection
variable, so any changes made to the copycomp
variable doesn't need to assign it back to the collection like this :
service.subComponent1 = copycomp ;
since it is a class type and referring to the same object.
But I am passing the same reference to UpdateService1Data()
, then why do I need to make use of ref keyword? Why can't I just pass the variable? If updating works in Update function then why can't it work in UpdateService1Data() . I am visualizing it as the reference or the address to the SubComponent1 class is passed everywhere copycomp is used?