Storing converted value in a Variable

I am trying to store the value of an extracted string..I can't get it to work

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "123";

            int c = a[a.Length - 1];

            Console.WriteLine(c);
        }
    }
}

Shouldn't 3 be stored in the variable c? I want only 3 to be stored; I don't know what's wrong with this, the output is '51' how's that possible?

Jon Skeet
people
quotationmark

Shouldn't 3 be stored in the variable c?

No, the integer representation of '3' should be stored in the variable c, and indeed is.

You're effectively doing:

char tmp = a[a.Length - 1]; // tmp = '3'
int c = tmp; // Implicit conversion to int

The "character" representation in .NET is really a UTF-16 code unit... and converting from char to int just copies that code unit.

The code unit for '3' is 51, hence your output.

If you just use char instead, you'll be fine:

string a = "123";
char c = a[a.Length - 1];
Console.WriteLine(c); // "3"

If you want to get the "numeric value" of a character, you can use char.GetNumericValue:

int value = (int) char.GetNumericValue(a[a.Length - 1]);

Note that you have to cast to int because the return type is double, in order to cope with characters representing fractions, infinity etc.

If you're absolutely sure that the value is always an ASCII digit, you can just subtract '0':

int value = a[a.Length - 1] - '0';

Just be aware that that will silently give "odd" results for non-digit input though.

people

See more on this question at Stackoverflow