Search code examples
c#expression-treesdefault-parameters

how to pass a default parameter for an expression tree?


suppose i have the following function

Dal.Person.GetAllByAge<T>(int iAge, Expression<Func<Person, T>> OrderBy)  

i want to pass a default parameter for the Expression like OrderBy = e=>e.ID
so that if this parameter is not defined, the default is sorting by id.
how is this possible?


Solution

  • There are two problems here:

    • e => e.ID may not be valid for the T that's provided
    • You can only use constants in default parameters

    You can sort of work round this by doing:

    public Whatever GetAllByAge<T>(int age,
                                   Expression<Func<Person, T>> orderBy = null)
    {
        orderBy = orderBy ?? (Expression<Func<Person, T>>) 
                             (Expression<Func<Person, int>>)(e => e.Id);
        ...
    }
    

    (assuming the type of ID is int)

    ... but the cast will fail if T isn't int. Note that the double cast is for the "inner" part to originally tell the compiler what expression tree you want to convert the lambda expression to, and the "outer" part is to then force that to be the appropriate expression tree type for T.

    I'd be tempted to use overloading instead:

    public Whatever GetAllByAge(int age)
    {
        return GetAllByAge(age, e => e.ID);
    }