I have a toolkit that has many methods often taking Expression<Func<T,TProperty>> as parameters. Some can be single-level only (o=>o.Name), while some can be multi-level (o=>o.EmployeeData.Address.Street).
I want to develop something (MSBuild Task? Visual Studio Plugin? hopefully the first) that reads all the user’s .cs files, and gives build errors if the given parameter is not a property-expression (but something like o=>o.Contains("foo")), or if a multi-level expression is given where only a single-level is allowed.
I tried looking at compiled IL code first but since the expression trees are a C# compiler “trick”, in IL all I see is creating expression instances and such, and while I could check each if only MemberExpressions (and the correct number of them) are created, it is not so great.
Then Roslyn came to my mind. Is it possible to write something like this with Roslyn?
Yes, I think Roslyn and its code issues are exactly the right tool for this. With them, you can analyze the code while you type and create errors (or warnings) that are shown as other errors in Visual Studio.
I have tried to create such code issue:
The usage would be like this:
The code above has several issues:
semanticModel.GetSemanticInfo(memberAccess, cancellationToken).Symbolnear the end always returnsnull. This is because semantics of expressions trees is among the currently unimplemented features.