Wednesday, November 09, 2005

A generic Equal Method

Recently I faced a situation where I want to write an override of Equal method so that I can compare any 2 of my business objects. So the best way to do is to override the Equals and GetHashCode method in the base class for all business objects. The following code is a very simple way to compare any 2 objects:

public override bool Equals(object obj)
{
PropertyInfo [] properties=this.GetType().GetProperties(BindingFlags.Instance BindingFlags.Public BindingFlags.NonPublic);
foreach( PropertyInfo property in properties )
{
object obj1=property.GetValue(this, null), obj2=property.GetValue(obj, null);
if( (obj1==null && obj2!=null) (obj1!=null && obj2==null)
((obj1!=null && obj2!=null) && !obj1.Equals(obj2)))
return false;
}
return true;
}
public override int GetHashCode()
{
return base.GetHashCode ();
}

No comments: