Looking for a solution to an issue, I found the following code:
public interface IOrderExpression<TEntity>
{
OrderDirection Direction { get; set; }
LambdaExpression Selector { get; }
}
public static IQueryable<T> GetOrder<T>(this IQueryable<T> queryable, IList<IOrderExpression<T>> orderExpressions)
{
var firstOrderExpression = orderExpressions.First();
queryable = firstOrderExpression.Direction == OrderDirection.Ascending
? Queryable.OrderBy(queryable, firstOrderExpression.Selector as dynamic)
: Queryable.OrderByDescending(queryable, firstOrderExpression.Selector as dynamic);
[..]
}
At the first read, I thought:
this code can't compile, there is no
OrderBy
function in theQueryable
class that match a dynamic parameter.
But this code was marked as answer so I wrote it in my IDE to be sure. I wrote it this way: queryable.OrderBy(firstOrderExpression.Selector as dynamic)
and it does not compile as expected:
'IQueryable' does not contain a definiion for 'OrderBy' and the best extensions method overload 'Queryable.OrderBy' requires a receiver of type 'IQueryable'
But then, I wrote it exactly as I found it (using Queryable.OrderBy([..])
and it actually compiles (AND works at runtime!). This troubles me even more since I thought these two ways to call an extension method were identical...
Can someone explain me why this is allowed by the compiler?