Analyzing Dictionaries with String Keys that are Created Using ToDictionary

Oct 19, 2015

In the past we have covered working with types in your analyzer. We even built an analyzer that looked at generic types to work with dictionaries that have string keys to ensure they specified a string comparer. Since we already have that built, let's modify the existing analyzer to handle the ToDictionary call on an IEnumerable.

In order to modify this code, we need to do a few things. First, we need to change from using ObjectCreatoinExpressoin to InvocationExpression. Simply modify the syntax kind on the RegisterSyntaxNodeAction and update the cast to use an InvocationExpressionSyntax (Note, I also changed the variable name for clarity):

With that done, you can now run the code and it will catch all ToDictionary calls that return a Dictionary<string, X>, unfortunately, it will also catch any other method calls that happen to return a dictionary with a string key. To fix this, we need to check the method invocation to make sure it is a ToDictionary call. To do this, we can access the expression from the invocationNode and check the identifier text to see if is ToDictionary:

That is all you need to update to get a functioning analyzer that will handle the ToDictionary calls on an IEnumerable to ensure that you have dictionaries that explicitly define their string comparers. Obviously, this analyzer isn't perfect as it technically catches any method called ToDictionary regardless if the method is the IEnumerableToDictionary or some other ToDictionary. I'll leave that fix as an exercise for the reader :).