Paul said:
I think I got it working but not real happy with the implementation. It seems
like there would be some performance issues.
Any better ideas? Or, more importantly, will this actually work?
Public MustInherit Class BindableCollectionBase(Of T As IBusinessBase)
Inherits CollectionBase
Implements IBindingList
Implements System.Collections.Generic.IEnumerable(Of T)
Public Function GetEnumerator1() As
System.Collections.Generic.IEnumerator(Of T) Implements
System.Collections.Generic.IEnumerable(Of T).GetEnumerator
Dim lst As New List(Of T)
For Each item As T In Me
lst.Add(item)
Next
Well, yes, if you allocate a new list for every iteration there *will* be
performance issues... There's no need for that. See my previous post.
Public ReadOnly Property Current() As T Implements
System.Collections.Generic.IEnumerator(Of T).Current
Get
Try
Return lvLst(position)
Catch ex As Exception
Throw (New InvalidOperationException())
End Try
This is poor style (no pun intended).
First, do not catch the general type Exception -- you can't do anything
meaningful with it except perhaps at the outermost level of your
application, where you could log it. If for example the framework threw an
OutOfMemoryException or a ThreadAbortException here, you would not want to
mask this by throwing an InvalidOperationException.
Second, there is no point here to catching exceptions at all, because you
know exactly when the error should occur: when .MoveNext() hasn't been
called after creation or after .Reset(), or the last call to .MoveNext()
returned false. In this case, this all translates to "position" being valid.
Relying on List to throw an ArgumentOutOfRangeException for you can mask
errors and false assumptions, and they obfuscate the conditions under which
your code can and should fail.
Here, it isn't likely that List contains a bug, or that it will one day not
throw ArgumentOutOfRangeException, or that it will one day throw something
else, but in general it's unwise to depend on exact error behavior as you're
doing here. It's a simple matter of implementing the checks yourself so you
don't introduce the dependency in the first place.
This seems like a long sermon for a short bit of throwaway code, but I see
this sort of thing all the time and I'm usually the unlucky schmuck who has
to fix the resulting code, so I figure that spreading the word as much as
possible may make someone's life a tiny bit happier...