Bug in ObservableCollection?

TL;DR

Explains issues using ObservableCollection with generic types in .NET, why errors occur, and discusses workarounds and limitations when working with custom classes.

14 April 2008
Written by Martin Hinshelwood
2 minute read
Comments
Subscribe

I seam to be having a little problem. Now, this may be me being stupid, but I can’t get an ObservableCollection to work if you pass it a generic type!

For example, consider the following code:

Public Class ItemBitCollection(Of TItem)
    Inherits ObservableCollection(Of ItemBit(Of TItem))


End Class

Public Class ItemBit(Of TItem)

    Private m_item As TItem

End Class

Now, if you create an instance of ItemBitCollection you will see an error on the IDE regardless of wither you use a custom object type or a String type to initialise it:

image

Why does this not work? What is ObservableCollection doing that maybe it should not? Time to get Reflector out…

After some looking at the source I am still none the wiser. Even if you dumb down your classes to the bare minimum you cant pass a generic type into an ObservableCollection.

This is a limitation if you ask me…

Annoying solution:

If you create a fixed class type:

Public Class ItemBitCollection(Of TItemBit)
    Inherits ObservableCollection(Of TItemBit)

End Class

Public MustInherit Class ItemBit(Of TItem)

    Private m_item As TItem

End Class

Public Class DefaultItemBit
    Inherits ItemBit(Of String)

End Class

And then pass that class in it does work:

Dim o As New ItemBitCollection(Of DefaultItemBit)

Although this is a work around, it causes other problems in my code… Ahh well… worth a try…

Technorati Tags: .NET  WPF

Comments
Subscribe

What to read next

Article Engineering Excellence

Creating a better TFS Sticky Buddy (Core)

Explains building a flexible WPF data model in VB.NET for visualising hierarchical relationships using generics, ObservableCollections, and …

Read article
Article

Calling an object method in a data trigger

Explains how to call an object method in a WPF DataTrigger, the limitations with extension methods, and common errors when binding methods …

Read article