Skip to content

[API Proposal]: Add a RangeAttribute constructor supporting arbitrary IComparable ranges. #82526

Open

Description

@eiriktsarpalis

Background and motivation

The RangeAttribute currently supports int and double ranges out of the box using dedicated constructor overloads, however any other range necessitates using this overload requiring the operand type as well as string formatted representations of the lower and upper bounds. This only works for types supported by the TypeConverter class expressing limits in strings forces concerns around culture-sensitive formatting:

public class TimeSpanRangeAttribute : RangeAttribute
{
    public TimeSpanRangeAttribute(int minMilliseconds, int maxMilliseconds)
        : base(type: typeof(TimeSpan),
               minimum: TimeSpan.FromMilliseconds(minMilliseconds).ToString("c"),
               maximum: TimeSpan.FromMilliseconds(maxMilliseconds).ToString("c"))
    {
        ParseLimitsInInvariantCulture = true;
    }
}

I've been working on a prototype that adds a protected constructor which accepts arbitrary IComparable bounds directly.

API Proposal

namespace System.ComponentModel.DataAnnotations;

public partial class RangeAttribute
{
    public RangeAttribute(int minimum, int maximum);
    public RangeAttribute(double minimum, double maximum);
+   public RangeAttribute(IComparable minimum, IComparable maximum);

    [RequiresUnreferencedCode("Generic TypeConverters may require the generic types to be annotated.")]
    public RangeAttribute(Type type, string minimum, string maximum);
}

API Usage

The above example is now rendered as follows:

public class TimeSpanMillisecondRangeAttribute : RangeAttribute
{
    public TimeSpanMillisecondRangeAttribute(int minimumMs, int maximumMs)
        : base(TimeSpan.FromMilliseconds(minimumMs), TimeSpan.FromMilliseconds(maximumMs))
    { }
}

Alternative Designs

  • I marked the proposed constructor as protected, since marking it public would add OOTB support for things like string or long ranges using their built-in IComparable implementation. Marking it protected emphasizes its use as an extensibility point for user-defined derived validation attributes. If people thinks it is useful, we could mark as public instead.
  • Proposal leaves out IComparer support since the validator implementation is oriented around handling of IComparable values.

Risks

No response

cc @geeknoid @jeffhandley

Activity

  1. added
    api-suggestion
    on Feb 23, 2023
  2. ghost added
    untriaged
    on Feb 23, 2023
  3. removed
    untriaged
    on Feb 23, 2023
  4. added this to the Future milestone on Feb 23, 2023
  5. jeffhandley commented on Mar 25, 2023

    @jeffhandley
    Member

    @eiriktsarpalis I'm inclined to pull this into .NET 8 to group it with the other DataAnnotations enhancements we're making during the release. @geeknoid Would you be able to use this if it was in .NET 8?

    /cc @dotnet/area-system-componentmodel-dataannotations

  6. added
    api-ready-for-review
    and removed
    api-suggestion
    on Mar 27, 2023
  7. eiriktsarpalis commented on Mar 27, 2023

    @eiriktsarpalis
    MemberAuthor

    Sure, marking as ready for review.

  8. modified the milestones: Future, 8.0.0 on Mar 27, 2023
  9. geeknoid commented on Mar 27, 2023

    @geeknoid
    Member

    @jeffhandley Yes, I think we could use this in .NET 8

  10. added
    partner-impact
    on Mar 27, 2023
  11. added
    blocking
    on Apr 24, 2023
  12. terrajobst commented on Apr 25, 2023

    @terrajobst
    Contributor
    • We suggest to provide a RangeAttribute<T> that is abstract and constrains the parameters to have the same type.
    • We should consider a design where RangeAttribute<T> doesn't extend RangeAttribute such that we can constrain T to IComparable<T> rather than IComparable.
    namespace System.ComponentModel.DataAnnotations;
    
    public partial class RangeAttribute
    {
        // Existing:
        // public RangeAttribute(int minimum, int maximum);
        // public RangeAttribute(double minimum, double maximum);
        private protected RangeAttribute(Type type, IComparable minimum, IComparable maximum);
    }
    
    public abstract class RangeAttribute<T> : RangeAttribute
        where T: IComparable
    {
        protected RangeAttribute(T minimum, T maximum);
    }
    
    // Example usage:
    // 
    // public class TimeSpanMillisecondRangeAttribute : RangeAttribute<TimeSpan>
    // {
    //     public TimeSpanMillisecondRangeAttribute(int minimumMs, int maximumMs)
    //         : base(TimeSpan.FromMilliseconds(minimumMs),
    //                TimeSpan.FromMilliseconds(maximumMs))
    //     {        
    //     }
    // }
  13. added
    api-needs-work
    and removed
    api-ready-for-review
    on Apr 25, 2023
  14. jeffhandley commented on May 12, 2023

    @jeffhandley
    Member

    We will not pursue that revised design in .NET 8. Moving to Future and removing the blocking Marks issues that we want to fast track in order to unblock other important work label.

  15. modified the milestones: 8.0.0, Future on May 12, 2023
  16. removed
    blocking
    on May 12, 2023
  17. eerhardt commented on Oct 30, 2023

    @eerhardt
    Member

    Could we also use the IParsable interface and create:

    public sealed class ParsedRangeAttribute<T> : RangeAttribute<T> // this name could use some work
        where T : IComparable, IParsable<T>
    {
        public ParsedRangeAttribute(string minimum, string maximum);
    }

    Then users wouldn't need to create their own derived attribute classes to use types that are IParsable, like TimeSpan.

    Regarding naming, I think it would make more sense to use the Range<T> attribute name for the sealed class - the one that would be used in all the callsites. So maybe it would make sense to say:

    public abstract class ComparableRangeAttribute<T> : RangeAttribute
        where T : IComparable
    {
        protected ComparableRangeAttribute(T minimum, T maximum);
    }
    
    public sealed class RangeAttribute<T> : ComparableRangeAttribute<T>
        where T : IComparable, IParsable<T>
    {
        public RangeAttribute(string minimum, string maximum);
    }

    And then usages would look like:

    public class ResilienceStrategyOptions
    {
        [Range<TimeSpan>("00:00:00", "1.00:00:00")]
        public TimeSpan? MaxDelay { get; set; }
    }
  18. removed their assignment
    on Jan 17, 2025
  19. sbomer commented on Feb 4, 2025

    @sbomer
    Member

    This proposal would help make dotnet-monitor compatible with native AOT since it uses [Range(typeof(TimeSpan)), ...], for example here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.ComponentModel.DataAnnotationspartner-impact

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions