Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?
like image 704
Scre Avatar asked May 06 '14 09:05

Scre


People also ask

Does C have do-while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


2 Answers

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

like image 88
Adrian Ratnapala Avatar answered Oct 20 '22 00:10

Adrian Ratnapala


The behaviour is always the same: Passing by copying. In case the parameter is an object, the reference to the object is copied, so in fact you are working on the same object/list/whatever.

like image 27
Alexander Reifinger Avatar answered Oct 19 '22 23:10

Alexander Reifinger