0

i have this code for example:

string i = "100";

if(i[1]==0)
{
    MessageBox.Show("ok");
}

and I thought I should get "ok" but it doesnt work. What is i[1] here?

1
  • 2
    For this situation, i[1] is the character 0. You're comparing a char against an int. The number equivalent of the character 0 is 48. Since 0 == 48 is false, no alert is displayed. Commented Sep 21, 2011 at 18:43

5 Answers 5

6

Your comparison is using the wrong type. When you use an indexer with a string, the result is a char. Your if statement is using an int. You need to change your code to:

if(i[1] == '0')
{
    MessageBox.Show("Ok");
}
Sign up to request clarification or add additional context in comments.

Comments

5

You're comparing a string to an integer.

Try if (i[1] == '0').

Comments

2

i[1] is a char of '0' (Unicode U+0030), which is different than (int) 0.

Comments

1

char i[0] is compared against an integer

Comments

0

i[1] is the second character in the string, as arrays in c# are zero-based.

1 Comment

That's not what OP was asking. i[1] is a perfectly valid index into his string of length 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.