O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

C# 4.0 Interop Syntax Enhancements

Earlier in this chapter we saw C# 4.0’s support for embedding interop type information, which can remove the need for primary interop assemblies. That feature has no visible impact on syntax—it just makes life easier during installation. However, C# 4.0 has added a couple of features that offer better syntax for certain interop tasks.

Indexed Properties

Suppose you were to write the following C#:

someObject.MyProperty["foo"] = 42;

Before C# 4.0, there was only one way to interpret this: this code gets MyProperty, and then uses the returned object’s indexer to set a value of 42 using an indexer argument of "foo". Remember that properties are just method calls in disguise, so the code is equivalent to:

someObject.get_MyProperty().set_Item("foo", 42);

Note

When you write an indexer in C#, its getter and setter turn into methods called get_Item and set_Item.

Unfortunately, some COM components have properties that work in a slightly different way, and these are called indexed properties. Whereas in C#, indexers are a type-level feature, in COM, any individual property may define an indexer. COM properties are really just method calls just like in C#, but with an indexed property, the explicit code would look more like this:

someObject.set_MyProperty("foo", 42);

Indexed properties require fewer objects. The traditional C# interpretation requires MyProperty to return a distinct object whose job is to provide the indexer, through which we access the values of interest. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required