Note that there are some explanatory texts on larger screens.

plurals
  1. POImplicit Cast not happening in Expression Tree
    text
    copied!<p>I came across a scenario where I need to sort a list of custom type on different properties based on input. With the help of few articles, I was able to come up with generic implementation using LINQ.During unit testing, one of the test failed because implicit conversion was happening when lamda expression was created using Expression tree.</p> <p>Below I have put the sample code to understand the issue (Not sure why formatting was not getting correct, sorry for that)</p> <pre><code>static class ExtensionMethods { public static IEnumerable&lt;TSource&gt; Sort&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; unSortedList, Func&lt;TSource, object&gt; selector, bool isAscending) { return isAscending ? unSortedList.OrderBy(selector) : unSortedList.OrderByDescending(selector); } } class Program { class Student { public string Name { get; set; } public int Age { get; set; } } static void Main(string[] args) { var unOrderedStudents = new List&lt;Student&gt; { new Student{ Name="A", Age=20}, new Student{Name = "B", Age=19} }; //This Works var sortUsingLamda = unOrderedStudents.Sort&lt;Student&gt;(stud =&gt; stud.Age, true); //Exception - Expression of type 'System.Int32' cannot be used for return type 'System.Object' var sortUsingExpressionTree = unOrderedStudents.Sort&lt;Student&gt;( GetSortFunc&lt;Student&gt;("Age"), true); Console.WriteLine("Press any key to continue"); Console.ReadLine(); } private static Func&lt;T, object&gt; GetSortFunc&lt;T&gt;(string sortColumn) { var param = Expression.Parameter(typeof(T), "entity"); var propertyExpression = Expression.Property(param, sortColumn); var boxingExpression = Expression.Convert(propertyExpression, typeof(object)); return Expression.Lambda&lt;Func&lt;T, object&gt;&gt;(propertyExpression, param).Compile(); //after adding Convert expression issue got fixed //return Expression.Lambda&lt;Func&lt;T, object&gt;&gt;(boxingExpression, param).Compile(); } } </code></pre> <p>In the Main method, when I try to pass a Func delegate directly to Sort extension method it works but it fails with Expression tree.</p> <p>I found a <a href="http://connect.microsoft.com/VisualStudio/feedback/details/319387/when-lambda-is-converted-to-an-expression-tree-and-then-compiled-invocations-of-interface-methods-on-an-instance-of-type-parameter-constrained-with-that-interface-cause-boxing" rel="nofollow">similar</a> issue, but that talks about constrained type parameters. Is both the issues same? Can somebody help me understand the issue. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload