using ref with class C#
This is a common misconception of the use of ref
keyword in C#. Its purpose is to pass either a value or a reference type by reference, and you only need it in specific circumstances where you need a direct reference to the actual argument, rather than a copy of the argument (be it a value or reference itself). It is imperative not to confuse reference types with passing by reference in any case.
Jon Skeet has written an excellent article about parameter passing in C#, which compares and contrasts value types, reference types, passing by value, passing by reference (ref
), and output parameters (out
). I recommend you take some time to read through this in full and your understanding should become much clearer.
To quote the most important parts from that page:
Value parameters:
By default, parameters are value parameters. This means that a new storage location is created for the variable in the function member declaration, and it starts off with the value that you specify in the function member invocation. If you change that value, that doesn't alter any variables involved in the invocation
Reference parameters:
Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something by reference. Let's look at our previous examples, just changing the parameter to be a reference parameter:
To conclude: having read my reply and Jon Skeet's article, I hope that you will then see that there is no need whatsoever for using the ref
keyword in the context of your question.
For what you're doing you don't need to use ref. If you did pass the list using ref, you would be allowing the caller to change which list you're referencing, rather than just changing the contents of the list.
The only time you need to use ref with a reference type is if you're going to be creating a new object inside a function.
Example #1: ref
keyword not necessary.
// ...
List myList = new List();
PopulateList(myList);
// ...
void PopulateList(List AList)
{
AList.Add("Hello");
AList.Add("World");
}
Example #2: ref
keyword necessary.
// ...
List myList;
PopulateList(ref myList);
// ...
void PopulateList(ref List AList)
{
AList = new List();
AList.Add("Hello");
AList.Add("World");
}