How to: Cast Objects Returned by Office Applications

When you write managed code, by default you must specify an object's type. However, many methods and properties in the Microsoft Office primary interop assemblies return the type Object, because they have the capability to return several different types. When the object is returned, you must explicitly convert (in Visual Basic) or cast (in C#) the object to the correct type. Converting or casting the object enables IntelliSense for the object in the Code Editor.

For information about conversion in Visual Basic, see Implicit and Explicit Conversions and CType Function. For information about casting in C#, see () Operator (C# Reference).

The following procedure is an example of casting an object returned by a Microsoft Office application to a specific type for use in managed code. This example uses a document-level customization for Microsoft Office Excel.

To cast an object to a specific type

  1. Add a NamedRange control to cell A1.

    Dim NamedRange1 As Microsoft.Office.Tools.Excel.NamedRange = _
        Me.Controls.AddNamedRange(Me.Range("A1"), "NamedRange1")
    
    Microsoft.Office.Tools.Excel.NamedRange NamedRange1 = 
        this.Controls.AddNamedRange(this.Range["A1", missing], "NamedRange1");
    
  2. Cast the object returned from the ColumnWidth property of the named range to a Double and assign it to a variable.

    Although the underlying value of the ColumnWidth property is a decimal value, the property returns the value as an Object type. You must cast the Object to a Double to work with the decimal value directly.

    Dim width As Double = CType(NamedRange1.ColumnWidth, Double)
    
    double width = (double)NamedRange1.ColumnWidth;
    
  3. Display the column width of the NamedRange control in a dialog box.

    MessageBox.Show("Column width: " & width.ToString())
    
    MessageBox.Show("Column width: " + width.ToString());
    

See Also

Concepts

Writing Code in Office Solutions

Managed Code and Office Programming with Visual Studio

The Variable missing and Optional Parameters in Office Solutions

Other Resources

Controls on Office Documents

Samples and Walkthroughs (Office Development)