CODESNIP - Creating C# like indexers in VB.NET

Well, kind of :) I have a collection that I want to access in C# with an indexer, the only problem is that the collection is written in VB.NET as part of a library which I need to consume and would be foolhardy to try and rewrite in C#.

It’s just a mixture of attributes and keywords - but gets me from having to call

MyCollection.get_Item("key");

to

MyCollection["key"];

Just a stylistic approach on my end to keep the readability of my C# consumer as high as possible. This is basically what I used:

Imports System.Reflection
...
<DefaultMember("Item")> _ 
Public Class MyCollection
	Inherits System.Collections.CollectionBase

	Public Sub Add(ByVal NewObj As MyClass)
		List.Add(NewObj)
	End Sub

	...

	Default Public Overloads ReadOnly Property Item(ByVal Index As Int32) _
		As MyClass
		Get
			Return(CType(List.Item(Index), MyClass)
		End Get
	End Property

	Default Public Overloads ReadOnly Property Item(ByVal Key As String) _
		As MyClass
		Get
			Return(GetByKey(Key))
		End Get
	End Property
...
End Class

I don’t know if the Default on the properties are required, but this worked for me. So I’m not messing with it :) Hope this can help someone else out there.

[ Currently Playing : High and Dry - Radiohead - The Bends (4:05) ]