Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Having a user defined class, like this:

class Foo
    {
        public int dummy;

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

And having then 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 equals 2, meaning that my ArrayList contains basically pointers to my objects and not copies.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is already 2, as Array/Collections (to be precise any .NET Class/reference type) are passed by reference by default.

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

Why ->

  Consider var arr = new ArrayList();

The above statement first creates an ArrayList object and a reference is assigned to arr. (This is similar for any Class as class are reference type).

Now at the time of calling,

example ->    DummyMethod(arr) , 

the reference is passed by value, that is even if the parameter is assigned to a different object within the method, the original variable remains unchanged.
But as the variable points(refer) to same object, any operation done on underlying pointed object is reflected outside the called method.
In your example, any modification done in for each will be reflected in the arrayList.

If you want to avoid this behavior you have to create copy/clone of the object.

Example:

Instead of

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

Use

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...