Does C# pass a List<T> to a method by reference or as a copy?

Scre picture Scre · May 6, 2014 · Viewed 46.1k times · Source

Taking my first steps in C# world from C/C++, so a bit hazy in details. Classes, as far as I understood, are passed by reference by default, but what about eg. List<string> like in:

void DoStuff(List<string> strs)
{
    //do stuff with the list of strings
}

and elsewhere

List<string> sl = new List<string>();
//next fill list in a loop etc. and then do stuff with it:
DoStuff(sl);

Is sl in this case passed by reference or is a copy made so that I'd need to redefine the worker function like

void DoStuff(ref List<string> strs)
to actually act on sl itself and not a copy?

Answer

Adrian Ratnapala picture Adrian Ratnapala · May 6, 2014

It's passed by reference. List<T> is a class, and all class instances are passed by reference.