Thursday, March 3, 2011

How would I pass additional parameters to MatchEvaluator

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?

From stackoverflow
  • 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));
    
  • 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).

0 comments:

Post a Comment