Last night I was reading through some FxCop documentation, specifically through the FxCop Design Warnings (yeah, that’s what I do in my spare time) and I came across the “Do not expose generic lists” warning which states:
System.Collections.ObjectModel? That namespace was new to me, so today I did a little digging.
System.Collections.ObjectModel.Collection(Of T) is pretty straight forward and seems like a good class to inherit for generic collection objects.
System.Collections.ObjectModel.ReadOnlyCollection(Of T) is also interesting as it is a read-only wrapper around any object that implements the IList(Of T) interface.
But the one that excited me the most was System.Collections.ObjectModel.KeyedCollection. Here’s why.
Say I have a class Stock:
Public Class Stock Private _tickerSymbol As String Public Property Symbol() As String Get Return _tickerSymbol End Get Set(ByVal value As String) _tickerSymbol = value End Set End Property Public Sub New(ByVal tickerSymbol As String) _tickerSymbol = tickerSymbol End Sub End Class
Now if I want a Stocks class to represent a collection of Stock objects and I want to be able to access a specific Stock in that collection via its TickerSymbol all I have to write in my Stocks class is this:
Public Class Stocks : Inherits System.Collections.ObjectModel.KeyedCollection(Of String, Stock) Protected Overrides Function GetKeyForItem(ByVal item As Stock) As String Return item.Symbol End Function End Class
Now I can do this in my program code:
Dim stocks As New Stocks() stocks.Add(New Stock("GOOG")) stocks.Add(New Stock("YHOO")) Dim firstStock As Stock = stocks.Item(0) Dim googleStock As Stock = stocks.Item("GOOG")
And that works! Sweet!