I'm trying to create a Generic Action Delegate
delegate void ActionPredicate<in T1, in T2>(T1 t1, T2 t2);
and
public static ActionPredicate<T,string> GetSetterAction<T>(string fieldName)
{
ParameterExpression targetExpr = Expression.Parameter(typeof(T), "Target");
MemberExpression fieldExpr = Expression.Property(targetExpr, fieldName);
ParameterExpression valueExpr = Expression.Parameter(typeof(string), "value");
MethodCallExpression convertExpr = Expression.Call(typeof(Convert), "ChangeType", null, valueExpr, Expression.Constant(fieldExpr.Type));
UnaryExpression valueCast = Expression.Convert(convertExpr, fieldExpr.Type);
BinaryExpression assignExpr = Expression.Assign(fieldExpr, valueCast);
var result = Expression.Lambda<ActionPredicate<T, string>>(assignExpr, targetExpr, valueExpr);
return result.Compile();
}
and here is my caller
ActionPredicate<busBase, string> act = DelegateGenerator.GetSetterAction<busPerson>("FirstName");
and here is the business object
public abstract class busBase
{
}
public class busPerson : busBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
and here is the error what i get during compilation
Cannot implicitly convert type 'BusinessObjects.ActionPredicate<BusinessObjects.busPerson,string>' to 'BusinessObjects.ActionPredicate<BusinessObjects.busBase,string>'. An explicit conversion exists (are you missing a cast?)
My GetSetterAction is returning ActionPerdicate where as here T is busPerson and i am trying to store it in ActionPredicate keeping in mind about Contravariance. But it fails. i dont know how to proceed further. Please Help..!