This is probably a relatively simple oversight, but I can’t work out if I’m actually allowed to do this, or what might be a reasonable alternative (using in VS2010, C# .Net 4.0). I would strongly prefer to do this in the constructor if at all possible.
This is my class:
public class MyClass1<TOrderBy> : MyInterface1<MyType1, MyType2>
{
public MyClass1(IEnumerable<Guid> ids) : this(ids, 0, 10, a => a.Time, ListSortDirection.Ascending) { }
public MyClass1(IEnumerable<Guid> ids, int pageIndex, int itemsPerPage, Expression<Func<MyType2, TOrderBy>> orderBy, ListSortDirection sortDirection)
{
this.pageIndex = pageIndex;
this.itemsPerPage = itemsPerPage;
this.orderBy = orderBy;
this.sortDirection = sortDirection;
this.ids = ids != null ? ids.ToList() : new List<Guid>();
}
}
I get the error
Cannot convert expression type 'System.DateTime' to return type 'TOrderBy' when hovering over a => a.Time
and the errors Cannot convert lambda expression to delegate type 'System.Func<MyType2,TOrderBy>' because some of the return types in the block are not implicitly convertible to the delegate return type and Cannot implicitly convert type 'System.DateTime' to 'TOrderBy' when building.
As you can probably work out, I’m trying to build a class that takes information in the constructor to sort and page an IQueryable.
I want to supply defaults via overloaded constructors. How would I go about doing this?
Time is a
DateTime.TOrderBymight not be aDateTime, for example:So, you can’t do what you’re trying to do.
That
TOrderByis a big pain! The best idea would be to avoid the problem by not having aTOrderByas part of the class if you can help it. This answer shows a way to wrap the ordering expression to hide the TOrderBy from the outside world.