Working with Word Collections and using get_Item

Items in a Word collection are accessed in two different ways depending on whether the index into the collection is strongly typed or weakly typed. In the case of the KeyBindings collection for example, the index is strongly typed as an integer. As such, you can use the index operation ([]) to get to an item in a collection. The code looks like this:

 

Word.KeyBinding k = Application.KeyBindings[1];

For a collection for which the index into the collection is weakly typed as an object passed by reference, you must use the get_Item method of the collection. The Templates collection is an example of this. It has a weakly typed index of type object passed by reference. This is because you can either pass a string if you know the name of the template in the collection or you can pass an integer for the index of the template in the collection. To get a Template from the Templates collection by integer index you can write this code:

 

object index = 1;

Word.Template t = Application.Templates.get_Item(ref index);

To get a Template from the Templates collection by string name you can write this code:

object index = "Normal.dot";

Word.Template t = Application.Templates.get_Item(ref index);

Note that in both cases, you must declare an object first and then pass a reference to the object. When passing parameters by reference, you must always declare a variable first and then pass that declared variable by reference.

 

Visual Studio isn’t much help when trying to figure this out. It will encourage you to use the index operator even on a collection like templates through Intellisense prompts as shown below. But if you try to use the index operator when the index is passed by reference, you will get a compile error.

 Visual Studio Intellisense leads you down the wrong path of using the index operator with an object parameter passed by reference.

 

Furthermore, Visual Studio Intellisense doesn’t display get_Item as a method you can call on the collection in the popup Intellisense as shown below. Nonetheless, get_Item is an available method on Word collections.

Visual Studio Intellisense Doesn't Show the get_Item method.