How to Access a COM Indexed Property from C#

Posted by Matt | Filed under , , ,

I have been working on creating a rather complicated COM object system for work.  As a testing client, I am using C# to instantiate and make calls into my COM object instead of C++, simply because I find it easier to use COM objects from C# than I do from C++.

My COM object has an indexed property.  This means that I have a “propget” or “propput” method in my IDL that takes a parameter.  When working in the C# client, I’d like to have the call appear like the following:

MyObject obj = new MyObject(); 
string s = obj.MyProperty[3];
obj.MyProperty[4] = "Hello";

The problem is that C# will not access an indexed property as I would expect.  I’m not sure why C# does not support this, however, from what I’ve read about the upcoming C# 4.0, Microsoft still will not be supporting indexed properties from COM.

The workaround is simple, albeit maybe not obvious.  Every property in COM is implemented as a get and/or put function.  So the property “MyProperty” may have functions get_MyProperty() and put_MyProperty().  This is what you’d have to call if you were using a C++ client.  To access the indexed property, we can modify the above code as follows:

MyObject obj = new MyObject(); 
string s = obj.get_MyProperty(3);
obj.put_MyProperty(4, "Hello");

This allows us to access the indexed property.  But the code is not as elegant as if the object were a natural C# object.

Comments

March 12, 2009 19:09

trackback

Trackback from DotNetKicks.com

How to Access a COM Indexed Property from C#

DotNetKicks.com

July 14, 2009 13:38

Baby Shower Ideas

This is very true. C# allows you to access COM objects through a much more easier process than C++.  Achieving a similar output in C++ is rather complicated.

Cheers, Yameer, Baby Shower Ideas

Baby Shower Ideas United States

Comments are closed