What is Char.IsNumber() in C#?

Overview

Char.IsNumber() is a C# method that is used to check whether a certain character or character in a string at a specified position is categorized as a number or not.

If it is a number, then a Boolean True value is returned. If it is not a number, then a False value is returned.

Syntax

// for a character
IsNumber(Char)

// for a string
IsNumber(String, Int32)

Parameters

Char: This is the character we want to check to see if it is a number.

String: This is the string that contains the character we want to check. We specify the character in this string by using its index position in the string.

Int32: This represents the index position of a character in a string.

Returned value

The value returned is a Boolean value. It returns True if the character is a number. Conversely, it returns False if the character is not a number.

Code

In the following example, we will demonstrate the use of the Char.IsNumber() method. We will create some characters and strings, and check if any of the characters are numbers or not.

// use System
using System;
// create a class
class NumberChecker
{
// main method
static void Main()
{
// create some characters
char ch1 = 'h';
char ch2 = '#';
char ch3 = '5';
// create some strings
string s1 = "Hi, 1234!";
string s2 = "whatever";
// check if characters are numbers
bool a = Char.IsNumber(ch1);
bool b = Char.IsNumber(ch2);
bool c = Char.IsNumber(ch3);
bool d = Char.IsNumber(s1, 5); // sixth position
bool e = Char.IsNumber(s2, 2); // third position
// print returned values
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.WriteLine(e);
}
}

Explanation

In the code above, we can see that:

  • Only ch3, which is '5', and the character at the sixth position in s1, which is 3, are numbers. This is why they returned True.
  • The rest all returned False, because they are not numbers.

Free Resources