Steven Rands Steven Rands - 22 days ago 5
C# Question

Regex to find C# async methods with missing "Async" suffix?

In C#, one of the conventions for asynchronous methods (those marked with the

async
keyword) is that their names should end with an "Async" suffix:

public async Task MyMethod(/* params */) ... <-- Bad, missing "Async" suffix
public async Task MyMethodAsync(/* params */) ... <-- Good, as per convention


I've been writing a lot of async code lately, and I'm concerned that I may have forgotten to put the "Async" suffix on some methods.

Is there any regex that I can use to find those methods that are marked with
async
but that do not have the "Async" suffix? If that's possible, can the reverse be done (ie. find methods that do have an "Async" suffix but that are not marked with the
async
keyword)?

I would be looking to paste the regex into the "Find In Files" dialog in Visual Studio, if that makes any difference to the answer.

I'm guessing that tools like FxCop, CodeRush or ReSharper may already warn about things like this, however the latter two are not an option given my workplace, and I'd rather not have to install & configure the former if I can accomplish this using a simple regex.

Answer

Here with Regex:

(?i)async.*(?<!async)\(

It looks for the keyword async and then at a "(" without ("?<!") async before it.

Edit: Better version. Thx @Andrew

Task\s+(\w+(?<!Async))\(

This will give you the methods with small written asyncs at the and as well. Furthermore it allows to use find and replace.