Converting a character representing a digit (0-9) to its integer equivalent is a frequent task in C#. This article explores four efficient methods, highlighting their strengths and weaknesses to help you choose the best approach for your specific scenario.
Table of Contents
Subtracting ‘0’
This method exploits the sequential ordering of characters in ASCII and Unicode. Subtracting the character ‘0’ from a digit character directly yields its integer equivalent. It’s concise and highly efficient but limited to ASCII digits (‘0’ to ‘9’).
using System;
public class CharToIntConversion
{
public static void Main(string[] args)
{
char digitChar = '3';
if (char.IsDigit(digitChar))
{
int intValue = digitChar - '0';
Console.WriteLine($"The integer value of '{digitChar}' is: {intValue}");
}
else
{
Console.WriteLine($"'{digitChar}' is not a digit.");
}
}
}
Using char.GetNumericValue()
The char.GetNumericValue()
method offers robust conversion, handling digits from various Unicode ranges. However, it returns a double
, requiring a cast to int
, and returns -1 for non-numeric characters.
using System;
public class CharToIntConversion
{
public static void Main(string[] args)
{
char digitChar = '7';
double numericValue = char.GetNumericValue(digitChar);
if (numericValue != -1)
{
int intValue = (int)numericValue;
Console.WriteLine($"The integer value of '{digitChar}' is: {intValue}");
}
else
{
Console.WriteLine($"'{digitChar}' is not a numeric character.");
}
}
}
Using char.GetDecimalDigitValue()
Similar to GetNumericValue()
, but specifically for decimal digits (0-9). It returns an int
directly and -1 if the input isn’t a decimal digit, making it efficient and straightforward.
using System;
public class CharToIntConversion
{
public static void Main(string[] args)
{
char digitChar = '9';
int intValue = char.GetDecimalDigitValue(digitChar);
if (intValue != -1)
{
Console.WriteLine($"The integer value of '{digitChar}' is: {intValue}");
}
else
{
Console.WriteLine($"'{digitChar}' is not a decimal digit.");
}
}
}
Using int.Parse()
int.Parse()
converts a string representation to an integer. Although seemingly less efficient for single characters, it’s advantageous when handling strings or requiring robust error handling. It throws a FormatException
if the input isn’t a valid integer.
using System;
public class CharToIntConversion
{
public static void Main(string[] args)
{
char digitChar = '5';
try
{
int intValue = int.Parse(digitChar.ToString());
Console.WriteLine($"The integer value of '{digitChar}' is: {intValue}");
}
catch (FormatException)
{
Console.WriteLine($"'{digitChar}' is not a valid integer.");
}
}
}
The optimal method depends on your context. For simple ASCII digits, subtracting ‘0’ is fastest. For broader Unicode support and error handling, GetNumericValue()
or GetDecimalDigitValue()
are preferable. int.Parse()
offers the strongest error handling but is least efficient for single characters. Always handle potential errors appropriately.