Convert char to integer in C#

Asked

Viewed 546 times

4

Reading a blog article, I came across the following syntax for converting char to integer:

string value = "123";
foreach (var c in value)
{
    if (char.IsDigit(c))
    {
        int digito = c - '0';
    }
}

I wonder why this conversion works.

3 answers

4


3

According to the documentation of the C#, the char can be converted implicitly to int

(... ) char can be converted implicitly to ushort, int, uint, long, ulong, float, double or `decimal.

However, beware of unexpected results. A explanation by @Virgilionovic justifies why operations like this:

char op1 = '3';
char op2 = '1';

Console.WriteLine("Resultado: " + (op1 + op2).ToString());

Does not result in 4:

`Resultado: 100`

Because (int)op1 is 51 and (int)op2 is 49.

See this example in dotnetfiddle.;

0

you must use Tostring() not to use ASC code and then Tryparse to verify that it is integer.

string value = "123";
foreach (var c in value)
        {
            short digito;
            if(Int16.TryParse(c.ToString(),out digito))
            {
                Console.WriteLine(digito);
            }                
        }
        Console.ReadKey();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.