Reputation: 4219
This should be self explanatory. I am trying to detect if the first char of the string foo is a negative sign '-'. This is just a test code to test it.
private void button1_Click(object sender, EventArgs e)
{
string foo = textBox1.Text;
bool negativeValue = foo[1]==('-');
//bool negativeValue = foo[1].Equals ('-');
if (negativeValue == true)
{
label1.Text = "First char is negative !";
}
else if (negativeValue == false)
{
label1.Text = "First char is not negative !";
}
}
The result is always false even if the first char in the text box is '-'. Why?
Upvotes: 0
Views: 85
Reputation: 23208
Index lookup in C# is zero-based. So you should call:
foo[0] == ('-')
Using 1
will lookup the second character.
EDIT: Also as an alternative (and perhaps more clear) you can always use:
foo.StartsWith("-")
That should work no matter how inebriated you are. :)
(Also, consider trimming the text input if you want to avoid excessive/accidental preceding spaces from user input)
Upvotes: 3
Reputation: 32827
You are using wrong index.With 1
you are actually referring to 2nd character
Use 0
bool negativeValue = foo[0]==('-');
Upvotes: 2