Monday, January 2, 2012

The difference between OfType and Cast in Reactive Extensions (RX).

OfType tries to convert an object to the defined type or ignores it if the value is not of the defined type.
public class Person
{
    public string Name { get; set; }
}

object value = new Person { Name = "Kinga" };

var source = Observable.Return(new object())
                       .Concat(Observable.Return(value))
                       .OfType<Person>()
                       .Select(p => p.Name);
==========
OnNext : Kinga
OnCompleted
==========
The Cast method propagates an OnError if the value is not convertable to the defined type and stops the subscription
object value = new Person { Name = "Kinga" };

var source = Observable.Return(new object())
                       .Concat(Observable.Return(value))
                       .Cast<Person>()
                       .Select(p => p.Name);
==========
OnError : Unable to cast object of type 'System.Object' to type 'Person'.
==========

No comments:

Post a Comment