MaPi
MaPi

Reputation: 1601

Casting IEnumerable to IList returns null

I'm calling my repo with a code that returns an

IEnumerable<MyEntity>

And when I try to materialize the result it only works if I do .ToList() on the result, but if I try a

as IList<MyEntity>

It gives null. Shouldn't they produce the same result?

Upvotes: 3

Views: 1706

Answers (2)

Yan
Yan

Reputation: 433

.ToList() converts your IEnumerable to List.
as IList ("tries to") cast your IEnumerable to IList.

There is a chance that your IEnumerable isn't an IList at all, a simple example could be class Dictionary:

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IEnumerable, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, 
    IReadOnlyCollection<KeyValuePair<TKey, TValue>>, ISerializable, 
    IDeserializationCallback

We can see that none of the above interfaces is an IList.
Edit: thanks to @patrick-hofman comment, it is important to check the whole chain of implementations in order to be sure that this class isn't an IList(which of course ok in that case).

That said, as we can see from IList signature:

public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable

IList is an IEnumerable, but IEnumerable is not an IList.

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 156968

Then your enumerable wasn't of a type that implements IList<T>, like List<T> or similar. as just casts the variable to the specified type if the instance is of that type. It doesn't make any conversion.

ToList() actually force creation of a new List<T>, so it is logical that the new instance created there does implement IList<T>.

Upvotes: 4

Related Questions