|
-
Mar 7th, 2007, 01:02 PM
#1
Thread Starter
Addicted Member
If & Equals
Can any1 tell me why the code inside the if statement isnt executed??
input = 2+2 in this case
Code:
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..
-
Mar 7th, 2007, 01:29 PM
#2
Re: If & Equals
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.
-
Mar 7th, 2007, 01:45 PM
#3
Re: If & Equals
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:
Code:
if (Object.Equals(input[curPos], '0') || ....
or you could compare directly
Code:
if (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
-
Mar 7th, 2007, 02:23 PM
#4
Thread Starter
Addicted Member
Re: If & Equals
thx bush, the '0' worked
-
Mar 7th, 2007, 02:39 PM
#5
Re: If & Equals
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.
-
Mar 7th, 2007, 07:27 PM
#6
Re: If & Equals
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|