How would i check if the value entered is an int in if statement?

Aaron soggi 246 Reputation points
2021-03-27T23:19:01.98+00:00

I would've used Try Parse but i don't want to use the value, i just want to check if its an integer or not.

if (txtCardNumber.TextLength < 16 || txtCardNumber.TextLength > 16)
            {
                MessageBox.Show("Please ensure that your card number is 16 digits long and in the correct format!");
            }
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-03-28T00:25:05.223+00:00

    You don't need to declare a var with TryParse, do it like this

    Add this class to your project (makes it reusable), it's known as a language extension.

    public static class StringExtensions    
    {
        public static bool IsNumeric(this string text) => double.TryParse(text, out _);
    
    }
    

    Use it

    if (txtCardNumber.Text.IsNumeric())
    {
    
    }
    

    Using double indicates it can represent an int, double essentially a number

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Sam of Simple Samples 5,546 Reputation points
    2021-03-28T00:32:44.123+00:00

    You do not say what txtCardNumber is but if it is a text box then I assume the relevant string is txtCardNumber.Text. If so then if (txtCardNumber.Text.All(Char.IsDigit)) will be true if all characters are a digit and false otherwise.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.