Explains issues using ObservableCollection with generic types in .NET, why errors occur, and discusses workarounds and limitations when working with custom classes.
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:
1Public Class ItemBitCollection(Of TItem) 2 Inherits ObservableCollection(Of ItemBit(Of TItem)) 3 4 5End Class 6 7Public Class ItemBit(Of TItem) 8 9 Private m_item As TItem 10 11End 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:
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:
1Public Class ItemBitCollection(Of TItemBit) 2 Inherits ObservableCollection(Of TItemBit) 3 4End Class 5 6Public MustInherit Class ItemBit(Of TItem) 7 8 Private m_item As TItem 9 10End Class 11 12Public Class DefaultItemBit 13 Inherits ItemBit(Of String) 14 15End Class
And then pass that class in it does work:
1Dim o As New ItemBitCollection(Of DefaultItemBit)
Although this is a work around, it causes other problems in my code… Ahh well… worth a try…
No related videos found.
If you've made it this far, it's worth connecting with our principal consultant and coach, Martin Hinshelwood, for a 30-minute 'ask me anything' call.
We partner with businesses across diverse industries, including finance, insurance, healthcare, pharmaceuticals, technology, engineering, transportation, hospitality, entertainment, legal, government, and military sectors.
Kongsberg Maritime
Philips
Lockheed Martin
Workday
Healthgrades
Hubtel Ghana
Higher Education Statistics Agency
CR2
MacDonald Humfrey (Automation) Ltd.
Ericson
Freadom
Capita Secure Information Solutions Ltd
Boxit Document Solutions
Schlumberger
SuperControl
Teleplan
Milliman
Jack Links
Department of Work and Pensions (UK)
Washington Department of Transport
Washington Department of Enterprise Services
Ghana Police Service
Royal Air Force
Nottingham County Council
Brandes Investment Partners L.P.
Lean SA
Slicedbread
Alignment Healthcare
Xceptor - Process and Data Automation
Schlumberger