Re: Can a 'ref' parameter be saved for later use?
- From: Peter Duniho <no.peted.spam@xxxxxxxxxxxxxxxxxx>
- Date: Tue, 24 Nov 2009 11:27:01 -0800
Helmut Giese wrote:
Hello out there,
I am passing a string[] to a form's constructor, it gets displayed in
a ListBox, the user can change it and in the end I want it back.
I have a solution I don't particularly like and thought about using a
'ref' parameter. Inside a function I can use it to 'pass back' data -
but in this scenario the 'passing back' will have to happen later. So
I thought I could declare a (normal) variable to be a 'ref' - but the
compiler doesn't like it.
// class variables
ref string[] strLstFromCaller; // compiler error
Form(ref string[] strLst) {
// save the reference to strLst "somehow"
strLstFromCaller = strLst;
}
btnClose_Click(...) {
// get the (possibly changed) ListBox's content
...
// and return it to the caller via strLstFromCaller
}
In C or C++ (where I come from) one would just use a pointer and go on
but here I wonder: How could I achieve what I want in C#?
I agree with Scott's suggestion, and will go a bit further and suggest that your proposal seems to be a fundamental misuse of passing by reference, even if you could get it to work (which in C# you can't).
Even in C/C++ it's a dangerous thing to capture a pointer to some data and save it for reuse later. You have to be very clear to client code about what kind of pointer they can pass to you, lest they pass you a pointer to something on the stack, or to an object that is going to be freed before your own code's use of the pointer.
C# just doesn't let you get into that situation by default. Instead, it strongly encourages you to use a more maintainable pattern, such as using some kind of container class like Scott suggested. And I agree, you should follow that encouragement.
Note that in .NET, there are a number of alternatives for dealing with deferred or asynchronous processing. So if you would care to be more specific about what you're _really_ trying to do (i.e. under what circumstances do you "want it back", with respect to the array passed to your form, and why is it insufficient to allow the form to modify the array itself so that your code can later observe changes to it...not that I'm a big fan of _that_ approach either, but at least it works directly in C#), as opposed to your chosen attempt at a mechanism for accomplishing that, you may get better advice than just "don't do that". :)
Pete
.
- References:
- Can a 'ref' parameter be saved for later use?
- From: Helmut Giese
- Can a 'ref' parameter be saved for later use?
- Prev by Date: Re: Why won't my floats add up?
- Next by Date: Database help
- Previous by thread: Re: Can a 'ref' parameter be saved for later use?
- Next by thread: Re: Can a 'ref' parameter be saved for later use?
- Index(es):
Relevant Pages
|