dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19k stars 4.03k forks source link

Reinfer nullable annotation of 'var' variables #58645

Open RikkiGibson opened 2 years ago

RikkiGibson commented 2 years ago

The real alternative here is to use flow analysis to determine if any later assignment to the same variable involves a maybe-null value, and only infer a nullable type if that is the case

I think this could be done using the infrastructure we already have to reinfer the nullability of type arguments during flow analysis. In the compiler layer the local symbol would always have an annotated type, but in public API it could have whatever best type we determined through flow analysis.

I don't think this would be more expensive, because we already have to do a nullable analysis when you query about things inside a method body with nullable enabled.

Originally posted by @RikkiGibson in https://github.com/dotnet/roslyn/issues/57974#issuecomment-1005062560

Related to #41245

RikkiGibson commented 2 years ago

I would be interested in doing a spike to see:

  1. how hard is it to implement in practice
  2. does it improve the user experience in practice

I think that language design input may be needed in order to make this change.

RikkiGibson commented 2 years ago

@ryzngard does "change var to explicit type" work as expected now even though we didn't make the change suggested in this issue?

sharwell commented 2 years ago

does "change var to explicit type" work as expected now

The tracking issue https://github.com/dotnet/roslyn/issues/41243 is still open.