Kmills94
1/2/2018 - 7:50 PM

Reflect Properties Changed

public async Task ObjectPropertiesChanged(TMdl newModel, TMdl oldModel)

{

    //Iterate through all properties using reflection

    foreach (var property in newModel.GetType().GetProperties())

    {

        //Fall through if property is not a navigation property or a overridden property and is a built-in c# type 

        if (!property.GetMethod.IsVirtual && property.PropertyType.Namespace == "System")

        {

            //Get property value

            var newData = newModel.GetType().GetProperty(property.Name).GetValue(newModel);

            var oldData = oldModel.GetType().GetProperty(property.Name).GetValue(oldModel);

            

            //Mitigate whitespace

            if (property.PropertyType == typeof(string))

            {

                newData = newData?.ToString().Trim();

                oldData = oldData?.ToString().Trim();

            }

            

            //Only Execute next block of code if there is a value present within oldData or newData or both

            if ((newData != null && newData.ToString() != "") || (oldData != null && oldData.ToString() != ""))

            {

                //object.Equals enforces equality check as the first check, 

                //and not (in)equality check which would be done with == operation because the types are not known until run time.

                if (!object.Equals(newData, oldData))

                {

                    //Property has been changed

                }

            }

        }

    }

}