Ref paramater made ugly

  • Thread starter Thread starter Brad Wood
  • Start date Start date
B

Brad Wood

I have a method that takes a ref string parameter. This is because it
will be called in loops and most of the time it will not need to modify
the paramater at all, so I preferred not to return a newly allocated
string object.

I need to pass items of an array list (can't use specialized collection
in compact framework) to this method. I can't pass the array item
directly because I get a compiler error (a ref or out argument must be
an lvalue). So this is what I'm doing:
string temp = (string)array;
obj.refMethod ( ref temp );
array = temp;

I didn't find a performance problem with this, but is there a better way
to write this?
 
Brad Wood said:
I have a method that takes a ref string parameter. This is because it will
be called in loops and most of the time it will not need to modify the
paramater at all, so I preferred not to return a newly allocated string
object.

I need to pass items of an array list (can't use specialized collection in
compact framework) to this method. I can't pass the array item directly
because I get a compiler error (a ref or out argument must be an lvalue).
So this is what I'm doing:
string temp = (string)array;
obj.refMethod ( ref temp );
array = temp;

I didn't find a performance problem with this, but is there a better way
to write this?


No. ArrayList only looks like an array because of C# indexers.

string temp = (string)arrayList;

is just syntactic sugar for

string temp = (string)ArrayList::get_Item(i);

and
arrayList = temp
is
ArrayList::set_Item(i, temp);

There's no better way to write this.

Even if the C# compiler somehow allowed you to write

obj.refMethod ( ref arrayList);

It would still have to call get_Item/set_Item, and would also need a
temporary variable to hold the result.

David
 
Not sure its better. But you could propably get rid of the ref method with
something like:

string temp = (string)array;
string result = obj.RefMethod( temp ); // Returns null if no change needed.
if ( result != null )
array = result;
 
Back
Top