Collection and struct address

P

PauloFor

Hi have :

struct A
{
public int val;
}

class OtherClass
{
private lis = new ArrayList();
public void Add(ref A element)
{
lis.Add(element);
}

public void SumAll(int num)
{
for (int i=0;i<lis.Count;i++)
{
A work = (A) list;
work.val += num;
lis = work;
}
}

}

in code :

A test1 = new A();
A test2 = new A();

test1.val = 5;
test2.val = 7;
OtherClass.Add( ref test1);
OtherClass.Add( ref test2);
OtherClass.SumAll(10);

here I want :
test1.val = 15 and test1.val = 17;

but I get :
test1.val = 5 and test2.val = 7;

What kind of collection is rigth for this ?


thks,
Paulo.
 
M

Mattias Sjögren

What kind of collection is rigth for this ?

No other collection will give you that behavior. You would have to
make A a class to make it work that way. When A is a struct you always
end upp passing copies of the data around (even if you use ref
parameters) and changing one copy does not affect others.



Mattias
 
J

Jon Skeet [C# MVP]

Mattias Sjögren said:
No other collection will give you that behavior. You would have to
make A a class to make it work that way. When A is a struct you always
end upp passing copies of the data around (even if you use ref
parameters) and changing one copy does not affect others.

Hang on - you *don't* always end up passing copies of the data around.
The call which passes the struct by reference doesn't make a copy of
the data. However, passing by reference can never let the called method
*store* a reference to the original variable anywhere, so after the Add
method has finished, the variable is "independent" again.
 
M

Mattias Sjögren

Hang on - you *don't* always end up passing copies of the data around.

Oops, right, I didn't mean to say that, but I realize that I just did.
:) Thanks for catching that. What I meant to say was that the
collection will store a (boxed) copy, whether or not the Add method
parameter is ref.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top