tt2lhp

Hi,

I am trying to write a function that allows passing different number of variables as references. I learned that we could use params modifier to achieve this. For example, I can declare my function as following:

void MyFunc(params object[] objs).

However, the variables will be passed in as values but what I really want is passing by references. I can get arround this by overloading MyFunc by incrementing the number of variables in the signature. For example:

MyFunc(ref object obj1)
MyFunc(ref object obj1, ref object obj2)
...and so on

but doing this is kind of annoying since I may need to pass in more or fewer variables later on.

Is there a generic way that we can pass different numbers of variables to a method in a simple way, like with the params modifier, by references

Thanks.
Tung.


Re: Visual C# Language How to pass multiple variables as references in a generic way???

Sean Fowler

As far as I know it's not possible to combine params and passing by ref.

However you may have misunderstood what happens when you pass reference types (e.g. your obj1 and obj2) by val and by ref. It's a very common misunderstanding though.

When passed by val it's only the reference to the object that's copied, not the object itself. The original reference to the object and the copy of the reference both point to the same object.

So if you change the object you're changing the original; there is no copy. The only difference is if, within your method, you're changing what obj1 or obj2 point to, for example if you do something like:

Code Snippet

objs[0] = new object();


If passed by val then this won't affect the calling method; its reference will still point to what it did when it called your method.

However if you were somehow able to pass it by ref then this would also change what the calling method's reference points to, as it's the same reference.

If you'd like some sample code and a more detailed explanation check out my last post here.

Sorry if you know this and it hasn't helped, but it's such a common misunderstanding I thought it worth mentioning.

In case you do need to change the reference in the calling method you could always do it manually:

Code Snippet

public void Test()
{
object[] objects = new object[2];
Address address = Address.GetByKey(1);
objects[0] = address;
MyFunc(objects);
address = (Address)objects[0];
}

private void MyFunc(params object[] objs)
{
objs[0] = new Address();
}



Sean