Skip to content

CODESNIP - Creating C# like indexers in VB.NET

Fri Nov 19 2004

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();

to

MyCollection[];

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:

 System.Reflection
...
<DefaultMember()> _ 
  MyCollection
	 System.Collections.CollectionBase

	  Add( NewObj  )
		List.Add(NewObj)
	 

	...

	     Item( Index  Int32) _
		 
		
			((List.Item(Index), )
		 
	 

	     Item( Key  ) _
		 
		
			(GetByKey(Key))
		 
	 
...
 

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) ]

💾 May the source be with you. v3.2.419