FistiPaul
FistiPaul

Reputation: 53

.Equals or == return false, always

here is my problem.

I have 2 datatables filed with the exact same content, but i don't get why, when i compare their columns neither == nor .Equals can return true.

public void btn_Source_Click(object sender, EventArgs e)
    {            
        FichierSource.OuvertureSource();
        FichierSource.OuvertureBanque(comboBox1);
        int i = 0;
        foreach (DataColumn colonne in FichierSource.DTSource.Columns)
        {
            if (colonne == FichierSource.DTBanque.Columns[i]) 
                MessageBox.Show("Same");
            else
                MessageBox.Show("Not the same");
            i++;
        }
    }

Both of the datatable are field with 2 different CSV but both CSV have this content : Nom|Prenom|Date|numero Jack|Jared|17.04.17|1626010548999 Daphne|Orli|08.02.18|1660101461799 Dphne|Thane|04.06.18|1635062807599 Odessa|Gannon|08.02.18|1626032546899 Charles|Jena|22.11.16|1626040845399

I red a lot of same problems and i thought i understood the difference between == and .Equals but neither of those 2 return true, why ?

EDIT : here is a screenshot with both variable's value enter image description here

Upvotes: 0

Views: 296

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460228

  1. You don't compare the content of the DataTables but their DataColumns(which have a name and a type among other properties).
  2. If you use == you only compare references(you have to overload the == operator to compare by value which f.e. System.String does)
  3. Equals wouldn't help either because DataColumn doesn't override it. So Object.Equals is used which just compares references(similar to ==). Since those are are different DataColumn instances(same names but belong to different tables) both, Equals and ==, return false

If you want to compare all fields of one DataRow with all fields of another DataRow you can use DataRowComparerer.Default and you have to loop the rows instead of the columns:

var rowFieldComparer = DataRowComparer.Default;
for(int i = 0; i < FichierSource.DTSource.Rows.Count; i++)
{
    if (rowFieldComparer.Equals(FichierSource.DTSource.Rows[i], FichierSource.DTBanque.Rows[i]))
        MessageBox.Show("Same");
    else
        MessageBox.Show("Not the same");
}

Upvotes: 7

kami4ka
kami4ka

Reputation: 193

Both object are different instances. You should check primitive properties of them or write method to compare 2 objects.

Upvotes: 0

Related Questions