diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs index c18c91b3c2032..1f171fab27ccc 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs @@ -33,6 +33,8 @@ public override string FormatErrorMessage(string name) => Justification = "The ctor is marked with RequiresUnreferencedCode informing the caller to preserve the other property.")] protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { + ArgumentNullException.ThrowIfNull(validationContext); + var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty); if (otherPropertyInfo == null) { diff --git a/src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/CompareAttributeTests.cs b/src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/CompareAttributeTests.cs index 09ad56f6d44b8..445b18993ffd7 100644 --- a/src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/CompareAttributeTests.cs +++ b/src/libraries/System.ComponentModel.Annotations/tests/System/ComponentModel/DataAnnotations/CompareAttributeTests.cs @@ -99,6 +99,15 @@ public static void Validate_PropertyHasDisplayName_UpdatesFormatErrorMessageToCo Assert.Contains("CustomDisplayName", newErrorMessage); } + [Fact] + public static void IsValid_ValidationContextNull_ThrowsArgumentNullException() + { + var attribute = new CompareAttribute(nameof(CompareObject.ComparePropertyWithDisplayName)); + var compareObject = new CompareObject("test"); + + Assert.Throws(() => attribute.IsValid(compareObject.CompareProperty)); + } + private class DerivedCompareAttribute : CompareAttribute { public DerivedCompareAttribute(string otherProperty) : base(otherProperty) { }