Need desperate help with a simple compare

Please help... I am so frustrated with this bit of code. I dont understand why its not working. I am checking one field from another field if they are equal then you return a bool value of true. If they are false you load it to an array. I swear it sounds easy but when i run it and i have both fields on quickwatch they look equal it still goes to the else condition

string delimiterStr = ",";

char [] display;

char [] delimiter = delimiterStr.ToCharArray();

delimiterStr = "Total";

char [] total = delimiterStr.ToCharArray();

string [] splitString;

splitString = st.Split(delimiter,12);

if ((splitString[0].ToString()) != "")

{

display = splitString[0].ToCharArray(1,5);

if (display == total) ---> this is where the compare is. It goes to the else it seems every time.

return true;

else

cust[NumofRecords].Name = splitString[0];

}

cust[NumofRecords].DateofPurch = splitString[1];

return false;

}




Answer this question

Need desperate help with a simple compare

  • skiersdelight

    Thanks so much .. . what you say makes sense...

  • Rich John

    string to byte to char back and forth is a little bit of a pain anyway in C#... that was so easy in old C(++) - was all the same anyway ;)
  • StevenCardinal

    Well, you cannot compare to arrays like this...

    What you are comparing here are two objects of type System.Char[] there is no equal operator for this type, so the object references are compared and it is obviously not the same object instance, so the result is false - always. ToString does not work either, because then you get two times "System.Char[]" which would be always true.

    Use a small helper function like this one:

    static
    bool Compare(char[] a, char[] b)
    {
     
    if (a.Length != b.Length) return false;
     
    for (int i = 0; i < a.Length; i++)
       
    if (a [ i ] != b [ i ] ) return false;
     
    return true;
    }

    and compare like this:
    if (Compare(display,total)) ..


  • cananyonespeakenglish

    You're right, I assumed (wrong) that ToString would convert the char array to a string. Sorry to have induced you in error.


  • Scott Z

    Hi,
    although the strings within display and total might be the same, the comparison you're making is between pointers and not the strings themselves. Try something like:

    if(display.ToString() == total.ToString())
    {
    ....
    }


  • Need desperate help with a simple compare