Вопрос

I'm trying to make a method such as this

    public static bool GetInteger(string stringToConvert, out int intOutValue, int minLimit, int maxLimit)

I want it to check if the value is within the min and max range that I specify with the in-values. The parsing is just

            int.TryParse(stringToConvert, out intOutValue)

but how do I now check if the value of "intOutValue" is within range? It keeps telling me that it is a bool-value... Any help on how to do this would be greatly appriciated! (I'm pretty new to programming, and especially in c#)

Это было полезно?

Решение

If you're trying to do comparisons based on the result of the call to TryParse then therein lies your problem; that returns a boolean to indicate success or not (hence the Try). So you need to compare the inOutValue as that's what has been populated.

public static bool GetInteger(string input, out int result, int min, int max) {
  return int.TryParse(input, out result) && (result >= min && result <= max);
}

There is no need for an out param here, and I'd even say the method naming is bad, unless you actually want the value to be accessible after the fact.

Другие советы

It looks like you want to check if it is also in the given range, as well as a valid int. In which case you could do:

public static bool GetInteger(string stringToConvert, out int intOutValue, int minLimit, int maxLimit)
{
    bool parsed = int.TryParse(stringToConvert, out intOutValue);
    return parsed && intOutValue >= minLimit && intOutValue <= maxLimit;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top