Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing objects by reference or not in C#

Suppose I have a class like this:

public class ThingManager {
    List<SomeClass> ItemList;

    public void AddToList (SomeClass Item)
    {
        ItemList.Add(Item);
    }

    public void ProcessListItems()
    {
        // go through list one item at a time, get item from list,
        // modify item according to class' purpose
    }
}

Assume "SomeClass" is a fairly large class containing methods and members that are quite complex (List<>s and arrays, for example) and that there may be a large quantity of them, so not copying vast amounts of data around the program is important.

Should the "AddToList" method have "ref" in it or not? And why?

It's like trying to learn pointers in C all over again ;-) (which is probably why I am getting confused, I'm trying to relate these to pointers. In C it'd be "SomeClass *Item" and a list of "SomeClass *" variables)

like image 541
Piku Avatar asked Nov 30 '22 10:11

Piku


1 Answers

Since SomeClass is a class, then it is automatically passed by reference to the AddToList method (or more accurately, its reference is passed by value) so the object is not copied. You only need to use the ref keyword if you want to re-assign the object the reference points to in the AddToList method e.g. Item = new SomeClass();.

like image 69
Lee Avatar answered Dec 15 '22 02:12

Lee