I was reading the MSDN page about the ref
keyword and modified the example using a collection instead of an int, like so:
public static void Main(string[] args)
{
List<int> elements = new List<int>();
Method(elements);
foreach(int val in elements)
{
Console.WriteLine(val);
}
}
static void Method(List<int> addelements)
{
addelements.Add(1);
addelements.Add(20);
}
Why is it that without the ref
keyword I can see the ints added to the collection outside of the method? When it was just int val
I needed the ref to see what changes the method made, but with a List<int>
not so, why is this?
Update:
One more question, I now understand the ref
keyword and Lists
. With that in mind, is doing the following redundant:
public static void Main(string[] args)
{
List<int> elements = new List<int>();
elements = Method(elements);
foreach(int val in elements)
{
Console.WriteLine(val);
}
}
static List<int> Method(List<int> addelements)
{
addelements.Add(1);
addelements.Add(20);
return addelements;
}