Open sandboxFocusImprove this doc

COM010: Range Contract Cannot Be Satisfied by the Type

Severity Error
Reported by PostSharp.Patterns.Common
Message [<Attribute>] cannot be applied to "<Target>" because no value of the type <Type> is within its range.

Cause

The range contracts, RangeAttribute and the attributes derived from it such as GreaterThanAttribute, LessThanAttribute or StrictlyGreaterThanAttribute, check at run time that a value is between a minimum and a maximum. At build time, PostSharp compares the bounds with the range of the type of the field, property or parameter, ignoring Nullable<T>. When the minimum is greater than the largest value of the type, or the maximum is smaller than its smallest value, every assignment would fail, so PostSharp reports COM010.

<Attribute> is the name of the contract class, <Target> the field, property or parameter, and <Type> the name of its type.

In the following example, the StockLevel property is a byte, which cannot be greater than 255.

using System;
using PostSharp.Patterns.Contracts;

namespace Errors.COM010_Error;

public class Product
{
    // No byte value can be greater than 1000.
    [GreaterThan( 1000 )]
    public byte StockLevel { get; set; }
}

public static class Program
{
    public static void Main()
    {
        var product = new Product { StockLevel = 10 };
        Console.WriteLine( $"Stock level: {product.StockLevel}" );
    }
}
error COM010: COM010_Error.cs(10,17): [GreaterThanAttribute] cannot be applied to "Errors.COM010_Error.Product.StockLevel" because no value of the type Byte is within its range.

Resolution

  • Change the type of the field, property or parameter to a type that can hold the values of the range, for example short or int instead of byte.
  • Otherwise, correct the bounds of the contract so that they fall within the range of the type.

In the following example, StockLevel is a short, so the contract accepts 1500 and rejects 10.

using System;
using PostSharp.Patterns.Contracts;

namespace Errors.COM010_Fixed;

public class Product
{
    // A short can hold values greater than 1000.
    [GreaterThan( 1000 )]
    public short StockLevel { get; set; }
}

public static class Program
{
    public static void Main()
    {
        var product = new Product { StockLevel = 1500 };
        Console.WriteLine( $"Stock level: {product.StockLevel}" );

        try
        {
            product.StockLevel = 10;
        }
        catch ( ArgumentOutOfRangeException e )
        {
            Console.WriteLine( $"{e.GetType().Name}: {e.Message}" );
        }
    }
}
Stock level: 1500
ArgumentOutOfRangeException: The property 'StockLevel' must be greater than 1000. (Parameter 'value')

See Also

Reference

RangeAttribute
GreaterThanAttribute
LessThanAttribute

Other Resources

Contracts
Adding Contracts to Code