What is the advantage of passing a list as parameter as ref in C#? List is not a value type so every changes done on it will reflect after returning the function.
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
var list = new List<string>();
myClass.Foo(ref list);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
class MyClass
{
public void Foo(ref List<string> myList)
{
myList.Add("a");
myList.Add("b");
myList.Add("c");
}
}
I can remove "ref" and it will work fine. So my question is for what usage do we need to add ref keyword for lists, arrays... Thanks
The ref keyword causes an argument to be passed by reference, not by value. List is a reference type. And in your example you're trying to pass object by reference to method argument also using ref keyword.
It means that you're doing the same thing. And in this case you could remove ref keyword.
ref is needed when you want to pass some Value type by reference. For example:
class MyClass
{
public void Foo(ref int a)
{
a += a;
}
}
class Program
{
static void Main(string[] args)
{
int intvalue = 3;
var myClass = new MyClass();
myClass.Foo(ref intvalue);
Console.WriteLine(intvalue); // Output: 6
}
}
Some additional specification information you can find there: ref (C# Reference)
This will create new list and it will replace list
variable from outside:
public void Foo(ref List<string> myList)
{
myList = new List<string>();
}
This will not replace list
variable from outside:
public void Foo(List<string> myList)
{
myList = new List<string>();
}
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