PDA

Click to See Complete Forum and Search --> : If & Equals


carstenht
Mar 7th, 2007, 12:02 PM
Can any1 tell me why the code inside the if statement isnt executed??
input = 2+2 in this case


while (curPos < length)
{

if (input[curPos].Equals("0") || input[curPos].Equals("1") || input[curPos].Equals("2") || input[curPos].Equals("3") || input[curPos].Equals("4") || input[curPos].Equals("5") || input[curPos].Equals("6") || input[curPos].Equals("7") || input[curPos].Equals("8") || input[curPos].Equals("9"))
{
System.Console.Write("TEST");

tmpexp += input[curPos];


}


temp += Convert.ToInt32(tmpexp);





curPos++;



}


I know the problems lies in the use of Equals, but cant isolate the problem..

Harsh Gupta
Mar 7th, 2007, 12:29 PM
Is the input[] array of type "int"??

If so, then try if (input[curPos].Equals(0) || input[curPos].Equals(1)) (without quotes) and so on.

bushmobile
Mar 7th, 2007, 12:45 PM
Equals compares object references, clearly input[curPos] and "0" don't refer to the same object (they don't even refer to the same type).

If you want to use equals then it should be like:if (Object.Equals(input[curPos], '0') || ....or you could compare directlyif (input[curPos] == '0' || ...but surely using some RegExp would be better suited here.

note: someone correct me if I'm wrong - C# still v. new to me

carstenht
Mar 7th, 2007, 01:23 PM
thx bush, the '0' worked :)

bushmobile
Mar 7th, 2007, 01:39 PM
ah yes, input[curPos].Equals('0') works fine

guess it was just the wrong type that was the problem, not the reference mumbo jumbo i was on about.

jmcilhinney
Mar 7th, 2007, 06:27 PM
What Equals does exactly is compare the values of two stack variables. If the variables are a reference type then that means that two memory addresses are being compared. If the memory addresses are the same then the two variables refer to the same object. If the variables are a value type then that means that two values are being compared. So you see, Equals does EXACTLY the same thing for value types and reference types but because of their differing nature it appears like different behaviour.