Char to Int explicit Conversion in C#

7.1k Views Asked by At

I was trying to learn explicit conversion in c#.

First I explicitly converted string to int

namespace MyfirstCSharpCode
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "1234";
            int i = Convert.ToInt16(str);
            Console.WriteLine(i);

        }
    }
}

it worked and the result is : 1234

Now I tried to convert char to int

namespace MyfirstCSharpCode
{
    class Program
    {
        static void Main(string[] args)
        {
            char str = '1';
            int i = Convert.ToInt16(str);
            Console.WriteLine(i);

        }
    }
}

And now the result is 49, the ASCII value of 1. How to get the char 1 instead of ASCII value. Please don't be too harsh its my first day in c# ;)..

1

There are 1 best solutions below

0
On BEST ANSWER

You hit the overload methods of Conver.ToInt16(char) , and char is a UTF-16 code unit and representing 1 is 49. You can use Int16.TryParse to safe parse the number (need in 16 bit sign number) in order to get the valid integer.

               string str = "1";  //  use string if your number e.g 122
               short number;  // convert to 16 bit signed integer equivalent.
               if (Int16.TryParse(str, out number))
               {  
                   Console.WriteLine(number);

               }