C# Char to Int – How to convert a Char to an Int in C#

Introduction

It’s common to pull chars out of string, especially with regular expressions, and need to treat them like a true number. The easiest way to convert a char to in int in C# is: int.Parse(myChar.ToString()).

With that said, it’s not always the safest or most efficient method. Here I’ll give you a few different options for how to convert a char to an int, together with a discussion of their pros and cons and when each approach might appropriate.

Convert a Char to an Int using int.Parse()

As mentioned in the introduction, int.Parse() is the simplest method. If you’re certain that your char is an integer and are prepared to accept an exception being thrown if you’re wrong, then int.Parse() is your friend:

var myChar = '7';
var myInt = int.Parse(myChar.ToString());
Console.WriteLine(myInt);

/* this code outputs:
7
*/

Note the use of myChar.ToString() to convert the char into a string as there’s no overload of int.Parse() that takes a char. If you want further details on this, checkout the official docs.

But do bear in mind that you can expect a System.FormatException if the character you enter isn’t an int. You couple wrap this statement in a try catch block, but there is a neater way to handle these cases using int.TryParse:

Convert a Char to an Int using int.TryParse()

If you’re not sure if your character represents an integer, but you want to try converting it anyway, then int.TryParse() is for you. Here’s an example of how to use it:

int result;
if (!int.TryParse(myChar.ToString(), out result))
{
  // Do something else
}

Of if you’re after a more complete example:

using System;

public class Program
{
  public static void Main()
  {
    var myChars = new char[] {'9', 'z', '½'};
    foreach (var myChar in myChars)
    {
      if (!int.TryParse(myChar.ToString(), out var result))
      {
        Console.WriteLine($"the char {myChar} does not represent an integer");
      }
      else
      {
        Console.WriteLine($"{result} is of type {result.GetType()}");
      }
    }
  }
}

/* this code outputs:
9 is of type System.Int32
the char z does not represent an integer
the char ½ does not represent an integer
*/

Using int.TryParse() is safe, in that it’s not likely to throw exceptions, and in my opinion it wins on the readability front. That said, keep reading for some faster, more concise and some might argue more correct options. In particular, the eagle eyed among you might have noticed in the above example that the char ½ does not represent an integer. That’s true, but it does represent a number! so how can we parse ½, ¾ or the other fraction symbols?

Convert a Char to an Int using Char.GetNumericValue()

The Char.GetNumericValue() method can be used to convert a char or a string to a double as follows:

var number = (int)Char.GetNumericValue(myChar);

Or for a more complete example:

using System;

public class Program
{
  public static void Main()
  {
    var myChars = new char[] {'9', 'z', '½'};
    foreach (var myChar in myChars)
    {
      var number = Char.GetNumericValue(myChar);
      var myInt = (int)number;
      
      if (number == -1)
      {
        Console.WriteLine($"{myChar} has no numberic value");
      }
      else if (myInt == number)
      {
        Console.WriteLine($"{myChar} converts to the integer {myInt}");
      }
      else
      {
        Console.WriteLine($"{myChar} converts to {number}, which is not an integer");
      }
    }
  }
}

/* this code outputs:
9 converts to the integer 9
z has no numberic value
½ converts to 0.5, which is not an integer
*/

One of the things I like about char.GetNumericValue is is that ½ correctly converts to 0.5, but although it’s a number (actually a System.Double) it’s not an int, so not really appropriate for this article.

Also, when a character like ‘x’ is parsed using Char.GetNumericValue, no exception is thrown. Instead it’s given the result of -1, meaning you have to be careful and check explicitly for -1 errors in your code.

It’s due to these oddities that I generally prefer int.TryParse(), but if your dataset is likely to contain fraction characters char.GetNumericValue() is worth being aware of. That said, if you’re after ways to convert arbitrary strings to doubles then you might want to look at Double.TryParse(), but that’s a story for another post.

I mentioned above that there is a more concise and faster method available and I’d like to touch on those in the next section:

Convert a Char to an Int using character arithmetic

Before I go into the example, it’s worth explaining that each char is internally represented by a number, as can be seen in the following table:

We can check that this is true in c# as follows:

var myChars = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
foreach (var myChar in myChars)
{
  Console.WriteLine($"{myChar} is {Convert.ToInt32(myChar)} interally");
}

/* this code outputs:
0 is 48 interally
1 is 49 interally
2 is 50 interally
3 is 51 interally
4 is 52 interally
5 is 53 interally
6 is 54 interally
7 is 55 interally
8 is 56 interally
9 is 57 interally
*/

So why is that important? Well, it means we can use arithmetic to very quickly and easily convert the characters 0-9 into integers as follows:

var myInt = myChar - '0';

Or for a complete example:

using System;

public class Program
{
  public static void Main()
  {
    var myChars = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    foreach (var myChar in myChars)
    {
      var myInt = myChar - '0';
      Console.WriteLine($"{myChar} is now {myInt} which is of type {myInt.GetType()}");
    }
  }
}

/* this code outputs:
0 is now 0 which is of type System.Int32
1 is now 1 which is of type System.Int32
2 is now 2 which is of type System.Int32
3 is now 3 which is of type System.Int32
4 is now 4 which is of type System.Int32
5 is now 5 which is of type System.Int32
6 is now 6 which is of type System.Int32
7 is now 7 which is of type System.Int32
8 is now 8 which is of type System.Int32
9 is now 9 which is of type System.Int32
*/

So this is clearly concise, and it’s likely to be quick, so why isn’t it my preferred method?

Firstly, it’s really not obvious when reading this code back what we’re trying to achieve. I’d say this code isn’t very readable. You could argue that a well placed comment could fix that:

// Convert the char into an int - for details see
// https://csharpsage.com/c-char-to-int#Convert_a_Char_to_Int_using_character_arithmetic
var myInt = myChar - '0';

But my counter argument would be that comments become stale, and it takes more effort to even commented unreadable code, than code that is readable to begin with.

There’s also the question of what happens if we try and parse a character like ‘x’ with this method:

using System;

public class Program
{
  public static void Main()
  {
    var myChars = new char[] {'9', 'a', 'z', '½'};
    foreach (var myChar in myChars)
    {
      var myInt = myChar - '0';
      Console.WriteLine($"{myChar} is now {myInt} which is of type {myInt.GetType()}");
      if (myInt < 0 || myInt > 9)
      {
        Console.WriteLine($"{myChar} appears to be out of bounds");
      }
    }
  }
}

/* this code outputs:
9 is now 9 which is of type System.Int32
a is now 49 which is of type System.Int32
a appears to be out of bounds
z is now 74 which is of type System.Int32
z appears to be out of bounds
½ is now 141 which is of type System.Int32
½ appears to be out of bounds
*/

You’ll see that this method does not have any in built error checking, so we again need to be careful and check the bounds of the result ourselves.

I don’t know about you, but I’m not one of r being careful, so I like to stick to methods that do the fiddly stuff for me, like int.TryParse() described above.

Conclusion

There’s more than one way to skin a cat, and there’s more than one way to convert a char to in int in C#:

  1. If you’re confident it’s an int, use: int.Parse(myChar.ToString());
  2. If you’re not sure if your char represents an in, use: int.Parse(myChar.ToString(), out var myInt);
  3. If you want to handle fractional chars (like ½) consider using char.GetNumericValue(), but be aware it might turn -1 if the input doesn’t represent a char and the output is a double not an int;
  4. If you’re confident in your input is in the range ‘0’ – ‘9’ and speed is key, then you can do: var myInt = myChar – ‘0’;

I hope this has brought some clarity to the subject of converting a char to an int in C#. If you’re interested in improving your C# skills, you might want to check out my recent post on C# interview questions.

Leave a Reply

Your email address will not be published. Required fields are marked *