Passing objects by reference or not in C #

Suppose I have a class:

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 } } 

Suppose that "SomeClass" is a fairly large class containing methods and members that are quite complex (such as List <> s and arrays) and that there can be a large number of them, so not copying huge amounts of data around the program is important.

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

I like trying to learn pointers in C again and again ;-) (which is probably why I got confused, I try to associate them with pointers. In C, this will be "SomeClass * Item" and the list of variables "SomeClass *")

+4
source share
4 answers

Since SomeClass is a class, it is automatically passed by reference to the AddToList method (or, more precisely, its reference is passed by value), so the object is not copied. You only need to use the ref keyword if you want to reassign the anchor points to the object in the AddToList method, for example. Item = new SomeClass(); .

+17
source

Since SomeClass is a reference type, you do not need to use the ref keyword. If it were a value type, "ref" might be useful.

+2
source

Think of out as the way the parameter works as a return value.

So they are very similar:

 void Foo(out int result) { result = 5; } int Foo() { return 5; } 

And then think of ref as a way to resolve a parameter to both input and output.

So, in your example, if you declared your method:

 public void AddToList(ref SomeClass Item) 

Then the caller needs to write something like:

 SomeClass i = null; obj.AddToList(ref i); 

This would be illegal, for example:

 obj.AddToList(ref new SomeClass()); 

They will be forced to pass the variable name, not the expression, so the AddToList method can store the value in the variable. By adding the ref prefix, you allow your method to turn the passed variable into another object.

+1
source

If you ever need to use the original value of the user ref parameter. If not, use. For reference:

http://www.yoda.arachsys.com/csharp/parameters.html

http://msdn.microsoft.com/en-us/library/0f66670z(VS.71).aspx

0
source

Source: https://habr.com/ru/post/1309827/


All Articles