Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Check if two objects have same data [closed]

Tags:

c#

.net

Assuming that Obj1 and Obj2 are objects of the same class and the class contains only fields, is it possible to check whether the two objects have the same data if the fields of the class are not known?

like image 477
Coding man Avatar asked Oct 28 '25 12:10

Coding man


1 Answers

var haveSameData = false;

foreach(PropertyInfo prop in Obj1.GetType().GetProperties())
{
    haveSameData = prop.GetValue(Obj1, null).Equals(prop.GetValue(Obj2, null));

    if(!haveSameData)
       break;
}

This is based on assumptions (objects are of the same type), and could probably be refactored so that it's more defensive, but I'm keeping it readable so you can grasp what I'm trying to do.

In a nutshell, use reflection to iterate over the fields and check the values of each until satisfied that they don't match (no need to keep iterating after this).