Skip to content

Inferred nullability should flow into anonymous type fields #24018

@cston

Description

@cston

The anonymous type field in the following should be declared as string rather than string?. Instead, y.ToString() generates a warning that y may be null.

using System.Linq;
class C
{
    static void Main()
    {
        var x = new string[] { "" };
        var y = x.Select(s => new { s }).First().s;
        y.ToString();
    }
}

(jcouv update:)
I also noticed a reference to the feature flag in binding logic for anonymous types, which seems wrong (the feature flag should only affect diagnostics, but not symbols from binding).

    private BoundExpression BindAnonymousObjectCreation(AnonymousObjectCreationExpressionSyntax node, DiagnosticBag diagnostics)
        {
...
                //  calculate the expression's type and report errors if needed
                TypeSymbol fieldType = GetAnonymousTypeFieldType(boundExpressions[i], fieldInitializer, diagnostics, ref hasError);

                // build anonymous type field descriptor
                fieldSyntaxNodes[i] = (nameToken.Kind() == SyntaxKind.IdentifierToken) ? (CSharpSyntaxNode)nameToken.Parent : fieldInitializer;
                fields[i] = new AnonymousTypeField(fieldName == null ? "$" + i.ToString() : fieldName, fieldSyntaxNodes[i].Location, 
                                                   TypeSymbolWithAnnotations.Create(fieldType, isNullableIfReferenceType: node.IsFeatureStaticNullCheckingEnabled()));  // <===== THIS SEEMS FISHY

...
            }

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions