28

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?

Ben Doom
  • 7,865
  • 1
  • 27
  • 30
Jon Tackabury
  • 47,710
  • 52
  • 130
  • 168

2 Answers2

31

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
  • 16,674
  • 4
  • 44
  • 56
  • 1
    An alternative way to do it based on this solution `text = Regex.Replace(text, @"some_pattern", new MatchEvaluator(match => MatchEvalStuff(match, otherData)));` – Ryan Pergent Jul 21 '19 at 12:21
  • Sorry, I know this is old, but any chance someone could extend this answer with the delegate declaration please, I can't wrap my head around it? – Jarrod McGuire Jan 19 '20 at 02:08
14

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
  • 47,710
  • 52
  • 130
  • 168