简体   繁体   中英

Strange behaviour of if-evaluation

I want to check, whether Arguments contains a string from ParameterSwitches. If that is the case, it should be deleted from Arguments.

The Problem is, even when pSwitch has the same value as Arguments[i], the condition doesn't come true and Arguments[i] = null; won't be executed.

I've tried it step-by-step with the debugger and just got more confused, because it confirmed my assumption.

string[] Arguments = new string[]{/*some strings*/};
string[] ParameterSwitches = new string[]{/*some strings*/};
for (int i = 0; i < Arguments.Length; i++)
{
    foreach (string pSwitch in ParameterSwitches)
    {
        if (pSwitch == Arguments[i])
        {
            Arguments[i] = null;
        }
    }
}

Could anyone imagine a way this could happen?

Thanks in advance

UPDATE: Oh girls and guys... Next time I use my glasses before asking a question here. There was a small white space after one of the strings. That was the problem. Trimming did the trick.

if (String.Equals(pSwitch.Trim().ToUpper(), Arguments[i].Trim().ToUpper()))
{
    Arguments[i] = null;
}

"Problem" solved

try this:

if(string.Equals(pSwitch.Trim(), Arguments[i].Trim(), StringComparison.OrdinalIgnoreCase))

I assume that your strings don't match because they are not trimmed, or case is wrong, any other case won't match your decription

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

I kinda think this is due to the dereference of Arguments[i] vs the for each loop that put the value of each iteration in a string object.

What happens if you change the inner loop to imperative code as you did in the outer loop, thus introducing another iteration variable. Or the other way around create two for each loops.

Mistake in array values, the code works.

private static void Main(string[] args)
{
    string[] Arguments = new string[] {"111", "222"};
    string[] ParameterSwitches = new string[] {"111", "222"};
    for (int i = 0; i < Arguments.Length; i++)
    {
        foreach (string pSwitch in ParameterSwitches)
        {
            if (pSwitch == Arguments[i])
            {
                // set breakpoint here to see
                Arguments[i] = null;
            }
        }
    }
}

try it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM