views:

790

answers:

2

I have a bit of code that looks like this:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));

I need to pass in a 2nd parameter like this:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));

Is this possible, and what would be the best way to do this?

+1  A: 

MatchEvaluator is a delegate so you can't change its signature. You can create a delegate that calls a method with an additional parameter. This is pretty easy to do with lambda expressions:

text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
Daniel Plaisted
+3  A: 

Sorry, I should have mentioned that I'm using 2.0, so I don't have access to lambdas. Here is what I ended up doing:

private string MyMethod(Match match, bool param1, int param2)
{
    //Do stuff here
}

Regex reg = new Regex(@"{regex goes here}", RegexOptions.IgnoreCase);
Content = reg.Replace(Content, new MatchEvaluator(delegate(Match match) { return MyMethod(match, false, 0); }));

This way I can create a "MyMethod" method and pass it whatever parameters I need to (param1 and param2 are just for this example, not the code I actually used).

Jon Tackabury