Search code examples
c#.netgenericsfuncsystem.reflection

How to convert Func<T1, bool> to Func<T2,bool> in C#


I tried to code a function using refelecion to convert a function Func< TSource, bool> to Func< TTarget, bool> but without success

This what i did:

static Func<TTarget, bool> Convert<TSource, TTarget>(Func<TSource, bool> func)
    {
        var result = func;
        result.GetType().GenericTypeArguments[1] = typeof(TTarget);
        return (Func<TTarget, bool>)result;
    } 

Edit:

In my case i've an object User as a DTO and don't want to share this DTO with other layers, it will be visible only by my service agent, Then, there is another Layer which has access to my service agent, in this layer i've another Object that represent a user let's say 'CustomUser'. Let's say that the different between 'User' and 'CutomUser' that the first has a property 'Password' and the second without it.

In my service agent, i've a function GetUser( Func< User, bool> func ) but in my 3rd party layer i can't see the object User, however, the object CustomUser is visible So, in my service agent layer, i want to create another function GetUser ( Func< CustomUser, bool >) that will be visible by other layers and this function calls directly the first hidden function GetUser(Func< User, bool> ) by using a converter

public CustomUser GetUser(Func<CustomUser, bool> func) {
    // var myUser = this.GetUser(ConvertFunc( func) ) ;
    // The rest of code before returning my customUser
}

Solution

  • Finally, The solution of @Grundy works for me correctly, I've just to create a function that convert an object User to CustomUser then i do the following:

    Func<User,bool> userFunc = u=>func(UserToCustomUser(u))
    this.GetUser(userfunc)