Extension Method To Compare 2 Objects
https://stackoverflow.com/questions/10454519/best-way-to-compare-two-complex-objects or use thispublic static class ObjectComparer
{
public static bool CompareObj(this object source, object destination)
{
if (!source.GetType().Equals(destination.GetType()))
return false;
var properties = source.GetType().GetProperties();
foreach (var item in properties)
if (!item.GetValue(source, null).Equals(item.GetValue(destination)))
return false;
return true;
}
}
Usage
Create 2 classes.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Sample obj1 = new Sample(10,"Anish");
Sample obj2 = new Sample(10, "Anish");
Sample1 obj3 = new Sample1(10, "Anish");
Sample obj4= new Sample(11, "Anish");
Console.WriteLine(obj2.CompareObj(obj1)); // returns True as all values match
Console.WriteLine(obj4.CompareObj(obj1)); // returns False
Console.WriteLine(obj3.CompareObj(obj1)); // returns False
Console.ReadLine();
}
}
public class Sample
{
public Sample(int x,string name)
{
Id = x;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
public class Sample1
{
public Sample1(int x, string name)
{
Id = x;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
Comments
Post a Comment