Mike Webb
Mike Webb

Reputation: 9003

How do I convert integers to characters in C#?

I am trying to convert an index of 1 to 27 into the corresponding uppercase letter. I know that in C++ I could type this:

char letter = 'A' + (char)(myIndex % 27);

This same code does not work in C#. How can I accomplish this task in C#?

EDIT: I'd rather not have to encode an enum or switch statement for this if there is a better mathematical solution like the one above.

Upvotes: 1

Views: 7540

Answers (6)

plinth
plinth

Reputation: 49179

Here is a table driven solution:

char ToUpperChar(int index)
{
    if (index < 1 || index > 26)
        throw new ArgumentOutOfRangeException("index");

    return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index-1]; // took out the % - it's range-checked above.
}

Upvotes: 6

soulia
soulia

Reputation: 503

How about an extension method?

    public static int Index(this char letter)
    {
        const int offset = 64;
        if(letter >= 'A' && letter <= 'Z')
            return (Convert.ToInt32(letter) - offset);
        return 0;
    }

//usage... char letter = 'A'; int index = letter.Index();

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

In C#, you'll have to do your casting slightly differently:

char letter = (char)('A' + (myIndex % 27));

However, your math might also be wrong, and this is probably closer to what you actually want:

char letter = (char)('A' + ((myIndex - 1) % 26));

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564403

When you add (or subtract) two characters, you get an Int32 in C#. This will work:

int letter = 'A' + (char)(myIndex % 27);

If you want a char, you need to explicitly cast it again:

char letter = (char) ('A' + (char)(myIndex % 27));

However, this most likely should actually be:

char letter = (char) ('A' + (char)((myIndex - 1) % 26));

Upvotes: 8

Vlad
Vlad

Reputation: 35584

char letter = (char)('A' + (myIndex-1)%26);

(edit out magic number, adjusted indices)

Upvotes: 4

Krisc
Krisc

Reputation: 1427

This should work...

byte upperA = 65;
byte index = 1;

char letter = (char)(upperA + (index % 27));

Console.WriteLine(letter);

I also like Reed's answer.

Upvotes: 0

Related Questions