Let’s say I have a method that calls another method with some parameters, something like this:
public void SomeMethod()
{
List<SomeObject> TheList = SomeQueryThatReturnsTheList();
TheList = DoSomeWorkWithList(TheList);
}
public List<SomeObject> WorkForList(List<SomeObject> TheListAsParameter)
{
foreach (SomeObject x in TheListAsParameter)
{
....
}
return TheListAsParameter;
}
As you can see, the method WorkForList returns the list it received. My question is this: if I don’t return the list and rewrite the signature as public void WorkForList(List<SomeObject> TheListAsParameter) is pass by reference in c# going to mean that TheList in SomeMethod is going to be updated with the work that’s done in the WorkForList method? If so, will the following code work the same:
public void SomeMethod()
{
List<SomeObject> TheList = SomeQueryThatReturnsTheList();
DoSomeWorkWithList(TheList);
}
public void WorkForList(List<SomeObject> TheListAsParameter)
{
....
}
Thanks.
Well if you don’t use the
refkeyword, its address will be passed by value, meaning you will be able to change its element, but you can’t initialized it or can’t assign it null. for example. If in your method you do:You will not see the difference in the caller.
You should see this article: Parameter passing in C# by Jon Skeet