I have two methods:
public void A(List<int> nums)
{
nums.Add(10);
}
public void B(out List<int> nums)
{
nums.Add(10);
}
What is the difference between these two calls?
List<int> numsA = new List<int>();
A(numsA);
List<int> numsB = new List<int>();
B(out numsB);
In general, I am trying to understand the difference between passing reference types as-is or as out parameters.
In your example, method B
will fail to compile, because an out
parameter is considered to be uninitialized, so you have to initialize it before you can use it. Also, when calling a method with an out
parameter, you need to specify the out
keyword at the call site:
B(out numsB);
And you don't need to initialize the numbsB
variable before the call, because it will be overwritten by the method.
Jon Skeet has a great article that explains the various ways to pass parameters: Parameter passing in C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With