Home > Net >  Why is my local variable potentially null, even though the method returns non-null?
Why is my local variable potentially null, even though the method returns non-null?

Time:06-06

I'm not sure if this is a bug in Visual Studio or C#...

If Expression.Parameter() returns a non-null ParameterExpression (no question mark), then why is a local variable that receives its return value being saved as potentially null? i.e. ParameterExpression? instead of ParameterExpression

enter image description here

I'm using ASP.NET 6.0.2 and Visual Studio 2022 v17.1.3

CodePudding user response:

Well, i can't tell you why the language designers designed it that way, but at least it's documented behavior (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var):

When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.

It has nothing to do with VS supposedly being smart as the other answer alludes to, it simply is how the var keyword is specified with respect to nullable annotation context being enabled.

CodePudding user response:

It might be that the new VS is smart enough to know that Expression.Parameter might return a null..

Even though it's not returning a nullable type, the VALUE that comes back could be null.

I believe in .NET 6 they have done some changes / being more strict on nullable types.

<PropertyGroup>
    <Nullable>enable</Nullable>
</PropertyGroup>

https://www.c-sharpcorner.com/article/how-to-handle-nullable-reference-in-net-6/

  • Related