ArrayList object references

The presence of a custom class, for example:

class Foo { public int dummy; public Foo(int dummy) { this.dummy = dummy; } } 

And with something like this:

 ArrayList dummyfoo = new ArrayList(); Foo a = new Foo(1); dummyfoo.add(a); foreach (Foo x in dummyfoo) x.dummy++; 

How much is a.dummy?

How can I create my ArrayList so that a.dummy is 2, which means that my ArrayList contains mostly pointers to my objects, not copies.

-2
source share
4 answers

This is already 2, since Array / Collections (more precisely, any .NET class / reference type) are passed by default link.

In fact, the reference variable is passed by value, but behaves like passed by reference.

Why →

  Consider var arr = new ArrayList(); 

The above statement first creates an ArrayList, and the reference is assigned to arr. (This is similar for any class, since the class is a reference).

Now during a call

 example -> DummyMethod(arr) , 

the link is passed by value, that is, even if the parameter is assigned to another object inside the method, the original variable remains unchanged.
But since variable points (refer) to the same object, any operation performed on the main pointed object is reflected outside the called method.
In your example, any modification made for each will be reflected in the array.

If you want to avoid this behavior, you need to create a copy / clone of the object.

Example:

Instead

 foreach (Foo x in dummyfoo) x.dummy++; 

Use

 foreach (Foo x in (ArrayList)dummyfoo.Clone()) x.dummy++; 
+1
source

It already contains links, not copies. Wherein:

 Foo a = new Foo(1); dummyfoo.Add(a); 

a reference is passed to a , not a copy.

Therefore, dummy will be first 1, and then 2 after increments.

In any case, you are better off using generics:

 List<Foo> dummyfoo = new List<Foo>(); Foo a = new Foo(1); dummyfoo.Add(a); foreach (Foo x in dummyfoo) x.dummy++; 
+2
source

You declared Foo as a class. Classes are reference types . This is already working. Try:

 class Program { static void Main(string[] args) { ArrayList dummyfoo = new ArrayList(); Foo a = new Foo(1); dummyfoo.Add(a); foreach (Foo x in dummyfoo) x.dummy++; Console.WriteLine(a.dummy); //Prints 2! } } class Foo { public int dummy; public Foo(int dummy) { this.dummy = dummy; } } 

Aside from the generic List<T> type, the obsolete ArrayList type is preferred.

+1
source

This is already 2 : your ideone code that checks that ..

Unlike value types (i.e., struct s), referenced (i.e., class ) objects are passed by reference.

PS Generics are available with C # 2.0, so consider using List<Foo> instead of ArrayList to increase type safety.

+1
source

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


All Articles