Arash
Arash

Reputation: 3071

Problem With Using Elements Of An String

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?

Upvotes: 0

Views: 61

Answers (5)

Praveen
Praveen

Reputation: 1449

char i[0] is compared against an integer

Upvotes: 1

Jamiec
Jamiec

Reputation: 136239

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

Upvotes: 0

Dave
Dave

Reputation: 11899

You're comparing a string to an integer.

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

Upvotes: 5

Justin Niessner
Justin Niessner

Reputation: 245499

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");
}

Upvotes: 6

Mark Cidade
Mark Cidade

Reputation: 100047

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

Upvotes: 2

Related Questions