How to check if a character is a digit in C#
Overview
A character can be an alphabet, symbol, etc. In other words, a character can be alphanumeric. In C#, we can use the IsDigit() method to check if a character is numeric or a digit.
The IsDigit() method can be used on a single character or on a string. In the case of a string, we have to specify the index position of the character in the string.
IsDigit() returns true if the character is a decimal digit; otherwise, it returns false.
Syntax
// on character
IsDigit(Char)
// on a string
IsDigit(String, int32)
Parameters
-
Char: The character we want to check. -
String: The string that we want to check to see if any character at index positionint32is a digit. -
int32: The index position of the character in a string we want to check.
Code example
In the example below, we create some strings and characters and see if certain characters are decimal digits or not.
Explanation
In the code above, line 17 and line 19 return true because the value of char1, which is 5, is actually a numeric value/digit. str1 has 3 at position 3, which is also a number.
The other lines return false because the values are not decimal digits.