Why isn't Generic Casting working on this section of code?
IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
IQueryable<object> list = _repository.GetAllBuckets().Cast<object>().AsQueryable();
return list == null ? default(T) : (T)list;
}
This is an error: Error 3 Cannot implicitly convert type 'T' to 'System.Linq.IQueryable'. Explicit conversion exists (are you missing the listing?)
I am implementing this interface:
IQueryable<T> FindAllBuckets<T>();
What is the problem?
Here's what I've tried:
-
IQueryable<T> IS3Repository.FindAllBuckets<T>() { IQueryable<object> list = _repository .GetAllBuckets() .Cast<object>().AsQueryable(); return list == null ? list.DefaultIfEmpty().AsQueryable() : list; }
You are casting list
in T
, but the return value FindAllBuckets
is of type IQueryable<T>
.
Depending on the return type, _repository.GetAllBuckets()
this should work:
IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
return _repository.GetAllBuckets()
.Cast<T>()
.AsQueryable();
}
Try the following:
IQueryable<T> IS3Repository.FindAllBuckets<T>()
{
IQueryable<T> list = _repository
.GetAllBuckets()
.Cast<T>()
.AsQueryable();
return list ?? new List<T>().AsQueryable();
}
The main problem with your original approach is that you were trying to return an instance T
, not an instance IQueryable<T>
.