C# Code Snippet - Validate (int) Integer

C# Code Snippet - Validate (int) Integer

C# Code Snippet - Validate (int) Integer

(C-Sharp) C# code snippets return the validated int value by checking validity of the given int and checking the int value range within the given minimum and maximum int range.

Bookmark:

C# Code Snippet - Validate (int) Integer

These .Net C# code snippets validate given int number. This method takes 4 arguments. Int value to validate, default value in case given value is not a valid int, minimum int value and maximum int value. Integer value read as a object which allows to pass the value in any form such as text, data reader value, int, object ..etc. Value will be check against the maximum and minimum value to make sure given value is in correct range. If the given value is less than minimum value, method will return the given minimum value. If the given value is greater than maximum value, method will return the given maximum value. In any case if the given value is not a valid int value, then default value will be return.

/// <summary>
/// Validate given integer value
/// </summary>
/// <param name="_Data">pass int value to validate</param>
/// <param name="_DefaultVal">default int value</param>
/// <param name="_MinVal">Minimum int value allowed</param>
/// <param name="_MaxVal">Maximum int value allowed</param>
/// <returns>Validated int value</returns>
public int ValidateInt(object _Data, int _DefaultVal, int _MinVal, int _MaxVal)
{
    int _val = _DefaultVal;

    try
    {
        if (_Data != null)
        {
            _val = int.Parse(_Data.ToString());

            if (_val < _MinVal)
                _val = _MinVal;
            else if (_val > _MaxVal)
                _val = _MaxVal;
        }
    }
    catch (Exception _Exception)
    {
        // Error occured while trying to validate
        
        // set default value if we ran into a error
        _val = _DefaultVal;

        // You can debug for the error here
        Console.WriteLine("Error : " + _Exception.Message);
    }

    return _val;
}


Here is a simple example showing how to use above function (ValidateInt) to validate int. In this example shows how to validate entered int value in textbox when user leaving textbox.

// Check the int value when user leaving the textbox after entering value
private void textBox1_Leave(object sender, EventArgs e)
{
    textBox1.Text = ValidateInt(textBox1.Text, 10, 5, 20).ToString();
}


C# Keywords Used:

  • int
  • int.Parse
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, Validate numbers, Validate integers
  • Programming Language : C# (C-Sharp)

External Resources:

Leave a comment