Cast object to another object generic having properties in common. using extension method (Generic)
This extension method can be used to cast one object to another object. objects should have common properties. i-e classes with different names but with same properties. For example in MVC if you use View model and actual model (pocco classes). you can cast view model to actual model.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
public static class Extensions
{
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
/// <summary>
/// Cast the object to target
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="myobj"></param>
/// <returns>Target Object</returns>
public static T Cast<T>(this object myobj) where T : new()
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
if (myobj.GetType().GetProperty(memberInfo.Name) != null)
{
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj, null);
propertyInfo.SetValue(x, value, null);
}
}
return (T)x;
}
}
0 Comments