Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Passing reference type directly vs out parameter

Tags:

c#

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.

like image 738
Davis Dimitriov Avatar asked Mar 26 '12 15:03

Davis Dimitriov


1 Answers

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#

like image 189
Thomas Levesque Avatar answered Sep 30 '22 05:09

Thomas Levesque