简体   繁体   中英

Cannot convert void to int when checking an int is within a range

I'm using this code and it's giving me an error saying that it cannot convert void to int:

    private static int aBtn;
    public static int ABtn
    {
        get => aBtn;
        set => aBtn = CheckArgumentRange(nameof(value), value, 0, 5);
    }

    internal static void CheckArgumentRange(
        string paramName, int value, int minInclusive, int maxInclusive)
    {
        if (value < minInclusive || value > maxInclusive)
        {
            throw new ArgumentOutOfRangeException(paramName, value,
                $"Value should be in range [{minInclusive}-{maxInclusive}]");
        }
    }

Can anyone see what's wrong and why it's giving this error?

You will need to return the value if it's not out of range. Otherwise the set doesn't receive an int.
So simply add return value; after your if and you should be good.

Edit: and of course change the return type from void to int.

    private static int aBtn;
    public static int ABtn
    {
        get => aBtn;
        set => aBtn = CheckArgumentRange(nameof(value), value, 0, 5);
    }

    internal static int CheckArgumentRange(
        string paramName, int value, int minInclusive, int maxInclusive)
    {
        if (value < minInclusive || value > maxInclusive)
        {
            throw new ArgumentOutOfRangeException(paramName, value,
                $"Value should be in range [{minInclusive}-{maxInclusive}]");
        }

        return value;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM