Analyze nullability inside anonymous types with Roslyn

224 Views Asked by At

Here's a piece of code I want to analyze with Roslyn:

object Method()
{
  var rnd = new Random();
  return new { First = "1", Second = rnd.NextDouble() > 0.5 ? "2" : null };
}

I would like to find out the nullability of the returned properties. I know how to find the ReturnStatementSyntax and its SemanticModel.

My problem is that C# doesn't create nullability annotations on anonymous types. The anonymous type above is { First: string, Second: string }, without annotations.

My understanding is that for anonymous types the compiler uses nullability based on data-flow analysis only (correct me if I'm wrong). When hovering Second, VS does correctly indicate that it's nullable string? at this location.

Using Roslyn (Microsoft.CodeAnalysis), how can I extract the information that the returned First property is non-nullable and Second is nullable?

1

There are 1 best solutions below

0
On BEST ANSWER

In the end it turns out that it does work as you'd expect.

I was fooled for a long time by a Roslyn limitation: LINQ expressions loose nullability annotations (as of April 2020) and that was my test case :(