Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Are AsObservable and AsEnumerable Implemented Differently?

The implementation of Enumerable.AsEnumerable<T>(this IEnumerable<T> source) simply returns source. However Observable.AsObservable<T>(this IObservable<T> source) returns an AnonymousObservable<T> subscribing to the source rather than simply returning the source.

I understand these methods are really useful for changing the monad within a single query (going from IQueryable => IEnumerable). So why do the implementations differ?

The Observable version is more defensive, in that you can't cast it to some known type (if it original were implemented as a Subject<T> you'd never be able to cast it as such). So why does the Enumerable version not do something similar? If my underlying type is a List<T> but expose it as IEnumerable<T> through AsEnumerable, it will be possible to cast back to a List<T>.

Please note that this isn't a question on how to expose IEnumerable<T> without being able to cast to the underlying, but why the implementations between Enumerable and Observable are semantically different.

like image 611
RichK Avatar asked Mar 26 '12 14:03

RichK


1 Answers

Your question is answered by the documentation, which I encourage you to read when you have such questions.

The purpose of AsEnumerable is to hint to the compiler "please stop using IQueryable and start treating this as an in-memory collection".

As the documentation states:

The AsEnumerable<TSource>(IEnumerable<TSource>) method has no effect other than to change the compile-time type of source from a type that implements IEnumerable<T> to IEnumerable<T> itself. AsEnumerable<TSource>(IEnumerable<TSource>) can be used to choose between query implementations when a sequence implements IEnumerable<T> but also has a different set of public query methods available.

If you want to hide the implementation of an underlying sequence, use sequence.Select(x=>x) or ToList or ToArray if you don't care that you're making a mutable sequence.

The purpose of AsObservable is to hide the implementation of the underlying collection. As the documentation says:

Observable.AsObservable<TSource> ... Hides the identity of an observable sequence.

Since the two methods have completely different purposes, they have completely different implementations.

like image 92
Eric Lippert Avatar answered Oct 05 '22 23:10

Eric Lippert