-1

I have a function which takes a custom delegate as parameter in order to achieve the following:

delegate T TryParseDelegate<I,O,T>(I input, O output);

private string[] ReadMultiStringValue (string propertyName, TryParseDelegate<string, string[], bool> tryParse)
{
  string cellValue = GetCellValue(propertyName);
  string[] values = null;

  if (tryParse(cellValue, values))
    return values;
  else
    throw new Exception("Invalid cell value");
}

Which I would call like so:

string[] parsedValue = ReadMultiStringValue("myProperty", (n,p) => ParseHelper.TryParseName(n, out p));

When I debug the code, everything seems to work properly, except "values" remains null after going through tryParse (and yet is updated correctly when inside the TryParseName method). I tried adding the out keyword to values, but I get the error "Argument 2 may not be passed with the out keyword".

What am I missing here?

DMX David Cardinal
  • 599
  • 2
  • 7
  • 19

3 Answers3

1

I tried adding the out keyword to values, but I get the error "Argument 2 may not be passed with the out keyword"

This is because you need to change the delegate first.

delegate T TryParseDelegate<I, O, T>(I input, out O output);
Stanislav Dontsov
  • 1,591
  • 11
  • 24
0

You need to change the output parameter to out parameter and pass it like so:

delegate T TryParseDelegate<I,O,T>(I input, out O output);


if (tryParse(cellValue, out values))

The reason why it doesn't work without out is, when you pass values the reference is copied then you pass that reference as out to TryParseName method. But it doesn't change the original values.

It's similar to doing this:

string x = "foo";
string y = x;
x = "bar"; // this won't change the y.
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

You haven't defined your delegate with an out parameter. Change it to this:

delegate T TryParseDelegate<I, O, T>(I input, out O output);
                                            //^^^ Add this

And call it like this:

if (tryParse(cellValue, out values))
DavidG
  • 113,891
  • 12
  • 217
  • 223