Aaron Thomas
Aaron Thomas

Reputation: 5281

Syntax when accessing array of strings

With the following:

string[] strArr = {
    "SOMETHING",
    "ELSE",
    "HERE"
};
var a = strArr['B' - 'A'];

What exactly is going on with the ['B' - 'A'], and where can I find documentation of this behavior?

Upvotes: 0

Views: 61

Answers (4)

Jacob Pitts
Jacob Pitts

Reputation: 47

As for the documentation, try char (C# Reference).

First, 'B' and 'A', which are character literals stored as 16 bit numbers, will resolve to a char with the value 1.

Second, the compiler recognizes that the expression 'B' - 'A' is of type char, but string[] has an indexer which takes an argument of type int. As noted in the documentation above, the char type can be implicitly converted to an int; so this is the choice the compiler makes.

Upvotes: 1

Zein Makki
Zein Makki

Reputation: 30052

In C#, there is a implicit conversion from char not int (but not the opposite). So int x = 'a'; compiles. Actually the compiler transforms your code to something else. Here is and original code, and the code generated by the compiler:

User Code:

string[] strArr = { "SOMETHING", "ELSE", "HERE" };
char left = 'B';
char right = 'A';
int index = left - right;
var a = strArr[index];

Generated Compiler code:

string[] strArr = { "SOMETHING", "ELSE", "HERE" };
char c = 'B';
char c2 = 'A';
int num = (int)c - c2; // 66 - 65
string text = array[num];

I wrote a details answer about this a week go. Check it out.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152624

There is an implicit conversion from char to int. The conversion from char to int gives you the UTF-16 code of that character. Since B (ASCII 66) is the next letter after A (ASCII 65) in UTF-16, B - A would be equal to 42-41 which would be 1.

so

strArr['B' - 'A']

is equivalent to

strArr[1]

Upvotes: 2

Travis J
Travis J

Reputation: 82337

That is implicitly converting character codes to integers. It is a terrible way to represent the number 1, being that B is 66 and A is 65.

The end result is that you get the [1] element ("ELSE").

This works because char implements the IConvertible interface, and has this supporting method

/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
    return Convert.ToInt32(m_value);
}

More at char.csreference source

Upvotes: 2

Related Questions