Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a COM indexed property from C#?

I am trying to mimic an old vb6 dll with a new .net one. The mimicry has to be perfect so that that callers don't know they are using a new .dll.

I have a curiousness though. In VB6 it has the following in the object library:

Property BankList(Index As Long) As String

But AFAIK property this can't be done in .net?

The closest I can get is creating a function that exhibits that behaviour but then the COM type goes from Property to Method.

Can anyone suggest how I would create that signature with a property?

like image 694
Jon H Avatar asked May 06 '11 15:05

Jon H


People also ask

What is an indexed property C#?

C# Indexers An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers.

What is an indexed property?

An indexed property is a variable property that serves as a selection filter for active processes. It can also be used in defining events for business event processing. This property holds a piece of data, such as a customer Id, application date, or amount.

Why indexers are used in C#?

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access as an array. The compiler will generate an Item property (or an alternatively named property if IndexerNameAttribute is present), and the appropriate accessor methods.

What statement do you use to implement an indexer?

To declare an indexer for a class, you add a slightly different property with the this[] keyword and arguments of any type between the brackets. Properties return or set a specific data member, whereas indexers return or set a particular value from the object instance.


1 Answers

You can adorn a regular indexer with the IndexerNameAttribute attribute to expose a name for it to other languages. I'm not sure if this will achieve your goal, though.

Unfortunately, C# only supports the calling of named indexers as part of COM interop, there is no supported language way of implementing your own (i.e., a class can only have the default indexer with an IndexerNameAttribute attribute).

You can create something that looks similar for C# callers by implementing a type with an indexer and then having a property of that type, but it doesn't map exactly to the VB6 equivalent you need.

See also: Using Indexers (C#)

Aside
As has been mentioned in other answers, while C# doesn't support named indexers, the .NET CLR and some other languages, such as VB.NET, do. You may want to consider changing your target language in order to get this feature.

like image 81
Jeff Yates Avatar answered Oct 06 '22 20:10

Jeff Yates