Stafford Williams
Stafford Williams

Reputation: 9806

Casting to Collection<interface>

With this:

public class Widget : IWidget {}

Why does collection2 == null here:

var collection1 = collectionView.SourceCollection as ObservableCollection<Widget>;
var collection2 = collectionView.SourceCollection as ObservableCollection<IWidget>;

Where SourceCollection is ObservableCollection<Widget>

Upvotes: 0

Views: 2314

Answers (1)

iDevForFun
iDevForFun

Reputation: 988

if the collection is declared as ObservableCollection<Widget> it cannot be cast to ObservableCollection<IWidget>. I believe this is possible in .NET 4 but not 3.5 or less - CORRECTION - refer Adam's comment below.

For the above to work you must declare the list as ObservableCollection<IWidget> then both casts will work. You should always use the interface type where possible anyway.

As an aside when you use the 'as' keyword this is called safe casting. It will return null if the cast is not possible. Explicit casting ... ie (ObservableCollection<IWidget>) collectionView.SourceCollection will throw an exception if the cast is not possible.

Upvotes: 1

Related Questions