tags:

views:

44

answers:

1

I have a method that was declared like this:

public ButtonObject CreateStandardButton(type1 arg1, type2 arg2, 
                         ItemClickEventHandler eventHandler, type3 arg3, type4 arg4)

ItemClickEventHandler has the usual (sender, e) arguments. However, we never ended up using the (sender, e) arguments, so we have a bunch of calls like this:

myButton = CreateStandardButton(myArg1, myArg2, 
                (sender, e) => MyButtonClick(), myArg3, myArg4);

and, because this project was upgraded to .NET 3.5 about 15% of the way through, many calls like this:

myButton = CreateStandardButton(myArg1, myArg2, 
                delegate { MyButtonClick(); }, myArg3, myArg4);

We call this method a lot, so it's really annoying to have to add the lambda for unused arguments over and over. Therefore, I want to change all usages to this overload:

public ButtonObject CreateStandardButton(type1 arg1, type2 arg2, 
                         Action eventHandler, type3 arg3, type4 arg4)

Which allows us to do this instead:

myButton = CreateStandardButton(myArg1, myArg2, 
                MyButtonClick, myArg3, myArg4);

The problem is that the usages of the old delegate syntax would require a cast to (Action) because they're ambiguous to the compiler. So, in order to remove the annoyance, I want to do a find and replace, presumably with regular expressions.

What's the regular expression to do this?

+1  A: 

Unfortunately you're going to have a really hard time finding a regular expression that gets the job done. To properly match a delegate expression in C#, the regular expression engine must support the notion of recursion because of the brace matching that is involved. Even with recursion, such regexes are usually fairly difficult to get right.

Depending on the size of you project, it may be quick to just make the change and let the delegate functions turn into a compilation error and quickly fix them up. It's annoying but will be likely faster and more accurate than trying to define a proper regex replace.

JaredPar
I don't think he needs to match the full delegate expression. He really only needs to match the `delegate` keyword itself, the part in braces can stay as is (it will just become a statement lambda).
Pavel Minaev
@Pavel, true but the question specified the full conversion.
JaredPar
Thanks for the excellent answer, Jared. I considered the possibility of just, but wanted to make sure it wasn't easy to do with a regular expression. It's probably a low-risk fix to just let them turn into compiler errors and fix manually.
Josh Kodroff