Home > OS >  Why is the use of [var x = new T()] resolving to [T?]?
Why is the use of [var x = new T()] resolving to [T?]?

Time:12-12

I am using VS2022, .NET 6, C# 10, with the nullability context enabled project-wide.

public static ModelEnumerationAttributeProperty FromPropertyInfo (PropertyInfo propertyInfo, object value)
{
    var property = ModelEnumerationAttributeProperty.FromPropertyInfo(propertyInfo);

    property.PropertyValue = value;
    property.PropertyValueString = value?.ToString();

    return (property);
}

The auto-detected type of the variable property is resolving to the nullable type ModelEnumerationAttributeProperty?.

It appears to be a simple constructor call to a vanilla class. Constructors can throw exceptions but cannot return null.

Snapshot

So why is the use of [var x = new T()] automatically resolving to <T?>?

UPDATE:* Here is the static overload that calls a constructor:

public static ModelEnumerationAttributeProperty FromPropertyInfo (PropertyInfo propertyInfo)
{
    var property = new ModelEnumerationAttributeProperty();

    property.PropertyInfo = propertyInfo;
    property.Type = propertyInfo.PropertyType;
    property.Name = propertyInfo.PropertyType.Name;
    property.FullName = propertyInfo.PropertyType.FullName ?? "";
    property.AssemblyQualifiedName = propertyInfo.PropertyType.AssemblyQualifiedName ?? "";

    property.PropertyName = propertyInfo.Name;

    return (property);
}

The compiler does not flag this overload and the return type if non-nullable. I might as well have called var o = new object();, and it would do the same thing.

CodePudding user response:

This is as defined by the language.

From the documentation for var:

Important

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.

  • Related