.Net Object Comparison Using Generics

Some time we need to compare two objects or properties or entities. For ex. we are going for save data to data base so we need to compare our old data and new data. If any changes are there then we will go for save otherwise we don't need.

Here is a simple example of Entity comparison using generics.

For demo purpose i am putting only one label on my screen, that will tell us, Input objects are similiar or not.

.aspx

<asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label>

In code behind i have taken an Entity Class and create two objects of the same. On page load, Assigning different values to both.

.aspx.cs

 // Entity for Details
        public class DetailsEntity
        {
            public string Name { get; set; }
            public string Number { get; set; }
        }

 // Object Compare Generics Class
       public static class ObjectComparator<T>
        {
           public static bool CompareProperties(T newObject, T oldObject)
            {
                if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
                {
                    return false;
                }
                else
                {
                    var oldProperties = oldObject.GetType().GetProperties();

                    foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

                            if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
                            {
                                return false;
                            }
                        }
                        catch
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }
        }

//On Page Load Event

            DetailsEntity objDetails1 = new DetailsEntity()
            {
            Name = "Himanshu",
            Number = "99885566"
            };
           
            DetailsEntity objDetails2 = new DetailsEntity()
            {
                Name = "Himanshu1",
                Number = "998855"
            };

            if (ObjectComparator<DetailsEntity>.CompareProperties(objDetails1, objDetails2))
            {
                lblResult.Text = "Object one and two are similar.";
            }
            else
            {
                lblResult.Text = "Object one and two aren't similar.";
            }

Result

If we will load both object with same values then result us



Comments

Popular posts from this blog

C# Copy files from one server to another

Export SharePoint Online Group Users to Excel using Powershell