passing indexers and properties by reference

  • Thread starter Thread starter tg.foobar
  • Start date Start date
T

tg.foobar

i'd like to do the following, but i don't think it's possible. can you
help me find a way to do this, or maybe a better way to write the code?


I have a list of items that need to be modified based on their data and
some other data as well. i planned on passing it by reference into a
function that modified their values. but it gave me the error "you
cannot pass indexers and properties by reference". The only way i know
of doing it is making temporary variables for the call, which is quite
cumbersome. code follows for clarity.

Thanks in advance!

actual error message:
error code: CS0206
"A property or indexer may not be passed as an out or ref parameter"

pseudocode:
class myclass
{
public class subclass
{
int i;
int j;
int k;
}

public bool foo(ref int first, ref int second, ref int third)
{
first = second * third;
}

public void start()
{
List<subclass> items = new List<subclass>();
//fill list with items
foreach( subclass sc in items )
{
// this line causes the error.
// cannot pass properties by reference
foo(ref sc.i, ref sc.j, ref sc.k);

// this, however, works
int tempi, tempj, tempk;
tempi = sc.i;
tempj = sc.j;
tempk = sc.k;
foo( ref tempi, ref tempj, ref tempk );
sc.i = tempi;
sc.j = tempj;
sc.k = tempk;
}
}
}
 
Unless this is a simplified version of what you want, why not just pass the
whole class by reference?
 
This is right, you can't pass a property/indexer by reference, since
properties and indexers represent actual methods.

What you need to do is get the value of the property/indexer, call your
method, changing the value, and then set the value back.

Hope this helps.
 
thanks for the reply...

and yes, it is a simplified version of what i want. the "subclass" i'm
using has a bunch of rectangles for drawing, and i call "foo" 4 times,
one for each point in the rectangle (left, top, bottom, right). so it
kinda looks like this in my code:

foreach( subclass sc in items )
{
foo( sc.somerect.left, sc.otherrect.left, sc.anotherrect.left, ..
);
foo( sc.somerect.right, sc.otherrect.right, sc.anotherrect.right,
.... )
...
}

i would like to abstract out the "left" "right" etc out of foo() so
that i can just call it multiple times.

but reading "nicholas paldino's" response below i think i can come up
with a solution. thanks!
 
i think i understand now, i didn't know the definition of "properties"
i guess. i thought properties also referred to just plain member
variables (without a get/set), but i see now that is not the case. And
it at least makes sense that they might not allow you to pass the
property set() function by reference because it doesn't match the ref
int type.

Thanks!
 
Back
Top