Unless the underlying object of the value returned from repository.GetData
matches what you are trying to cast it to then the result will always be null
. Because the generic element types of the method and what is actually return from repository.GetData
are different you will need to do some conversions to get the desired result
Assuming that MyObject
implements IMyObject
I can think of at least to ways using System.Linq
to get the result you seek.
Option 1: Cast<T>()
Casts the elements of an System.Collections.IEnumerable to the specified type.
First convert the content of temp
using the Cast<MyObject>()
linq extension and then use the ToList<T>()
extension method to get you resulting IList<MyObject>
public IList<MyObject> GetSomeData(string inputParam)
{
//repository.GetData returns IEnumerable<IMyObject>
var temp = repository.GetData(inputParam);
var list = temp.Cast<MyObject>().ToList();
return list;
}
Option 2: OfType<T>()
Filters the elements of an System.Collections.IEnumerable based on a specified type.
Filter the content of temp
using the OfType<MyObject>()
linq extension and then use the ToList<MyObject>()
extension method to get you resulting IList<MyObject>
public IList<MyObject> GetSomeData(string inputParam)
{
//repository.GetData returns IEnumerable<IMyObject>
var temp = repository.GetData(inputParam);
var list = temp.OfType<MyObject>().ToList();
return list;
}