Skip to content

[Microsoft.Extensions.Options] ValidateEnumeratedItems throws for null collection elements #130682

Closed

Description

@Arithmomaniac

Description

This bug was generated by Github Copilot with human review and editing.

DataAnnotationValidateOptions<TOptions> throws ArgumentNullException when a property annotated with [ValidateEnumeratedItems] contains a null element.

Reproduction Steps

Create a .NET 10 console application with the following files.

NullEnumeratedItem.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.9" />
  </ItemGroup>
</Project>

Program.cs:

using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;

var options = new Parent
{
    Children =
    [
        new Child { Name = "first" },
        null,
        new Child { Name = "third" },
    ],
};

var validator = new DataAnnotationValidateOptions<Parent>(name: null);
var result = validator.Validate(name: null, options); // Throws

Console.WriteLine(result.Succeeded);

public sealed class Parent
{
    [ValidateEnumeratedItems]
    public IReadOnlyList<Child?> Children { get; init; } = [];
}

public sealed class Child
{
    [Required]
    public string Name { get; init; } = string.Empty;
}

Run:

dotnet run

Expected behavior

Validation should complete without throwing and continue past the null element to validate later elements.

Either of these behaviors would be reasonable:

  • Return a validation failure identifying the null element, such as Parent.Children[1].
  • Skip null elements consistently, leaving item-nullability enforcement to a separate rule.

At minimum, the null element should not abort the complete validation operation.

Actual behavior

Validation throws before returning a ValidateOptionsResult:

System.ArgumentNullException: Value cannot be null. (Parameter 'instance')

The exception occurs when the recursive options validator passes the null element to Validator.TryValidateObject.

Regression?

Unknown. I did not test an earlier framework version.

The unguarded collection loop appears to have been introduced with runtime recursive options validation in dotnet/runtime PR #90275.

Known Workarounds

Pre-scan every property marked with [ValidateEnumeratedItems] and reject or remove null elements before calling DataAnnotationValidateOptions<TOptions>.

Catching ArgumentNullException outside Validate prevents the process from failing, but cannot resume at the next element because the private collection loop has already unwound. A custom IValidateOptions<TOptions> implementation is required for indexed errors plus continuation.

Configuration

.NET SDK: 10.0.301 (commit 96856fd726)
Host/runtime: 10.0.9 (commit 901ca94124)
Microsoft.Extensions.Options.DataAnnotations: 10.0.9
OS: Windows 10.0.26200
RID: win-x64
Architecture: x64

Other information

The .NET 10.0.9 implementation skips a null collection property, but does not skip null elements inside a non-null collection.

The [ValidateEnumeratedItems] loop passes every element directly to the private recursive helper, without a null guard:

int index = 0;
foreach (object item in enumerable)
{
res = TryValidateOptions(item, $"{qualifiedName}.{propertyInfo.Name}[{index++}]", results, ref errors, ref visited) && res;
}

The recursive helper is private, so callers have no per-item continuation or recovery hook:

private static bool TryValidateOptions(object options, string qualifiedName, List<ValidationResult> results, ref List<string>? errors, ref HashSet<object>? visited)
{
Debug.Assert(options is not null);
if (visited is not null && visited.Contains(options))

The helper ultimately calls Validator.TryValidateObject, which explicitly rejects a null instance:

public static bool TryValidateObject(object instance, ValidationContext validationContext,
ICollection<ValidationResult>? validationResults, bool validateAllProperties)
{
ArgumentNullException.ThrowIfNull(instance);

I searched open and closed issues in dotnet/runtime and dotnet/aspnetcore but did not find an existing report for this exact behavior.

Activity

  1. added
    untriaged
    on Jul 14, 2026
  2. dotnet-policy-service commented on Jul 14, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-componentmodel-dataannotations
    See info in area-owners.md if you want to be subscribed.

  3. tarekgh commented on Jul 14, 2026

    @tarekgh
    Member

    Thanks for the detailed report, I can repro this.

    The fix we'd go with is to skip null elements in the [ValidateEnumeratedItems] loop (advancing the index so the remaining items keep their real positions), rather than reporting the null as a failure. A couple of reasons this is the more reasonable behavior:

    • It matches what the validator already does one level up. A null property value is skipped today via if (value is null) continue;, so skipping a null element is the consistent extension of that.
    • The error format only ever describes a failing member inside an item, for example DataAnnotation validation failed for 'Parent.Children[0]' members: 'Name' with the error: 'The Name field is required.'. A null element has no member and no ValidationResult, so "reporting" it would require inventing a synthetic message with empty member names that doesn't match any other output from this validator. There's also no per-item [Required] semantic that would make a null element invalid on its own.

    Reporting null elements as errors would be a new, deliberate rule rather than a bug fix, so it's out of scope here. If someone wants item nullability enforced, that's better handled by a separate validation rule.

    Note this also affects the async path (ValidateAsync), which has the same unguarded loop, so the fix needs to cover both.

  4. removed
    untriaged
    on Jul 14, 2026
  5. added this to the 11.0.0 milestone on Jul 14, 2026
  6. dotnet-policy-service commented on Jul 16, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-extensions-options
    See info in area-owners.md if you want to be subscribed.

  7. added a commit that references this issue on Jul 16, 2026
    5453829
  8. locked and limited conversation to collaborators on Aug 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions