Thursday, July 10, 2014

C# - Assign one class properties to another class properties using reflection

Following code helpful to assign properties of one class to another class object

 public static void MapProperties<T1, T2>(T1 destinationClass, T2 sourceClass)
        {
            if (destinationClass != null & sourceClass != null)
            {
                Type destinationType = destinationClass.GetType();
                Type sourceType = sourceClass.GetType();


                foreach (PropertyInfo sourceProperty in
                    sourceType.GetProperties())
                {
                    if (sourceProperty.CanRead)
                    {
                        string propertyName = sourceProperty.Name;
                        Type propertyType = sourceProperty.PropertyType;

                        PropertyInfo destinationProperty =
                            destinationType.GetProperty(propertyName);
                        if (destinationProperty != null)
                        {
                            Type toPropertyType = destinationProperty.PropertyType;

                           if (toPropertyType == propertyType && destinationProperty.CanWrite)
                            {
                             object sourceValue = sourceProperty.GetValue(sourceClass, null);
                            destinationProperty.SetValue(destinationClass, sourceValue, null);
                            }
                        }
                    }
                }
            }

        }