I have an Outlook 2013 Add-in,
Outlook.MAPIFolder inboxFolder;
Outlook.Items mailInboxItems;
private void ThisAddIn_Startup(object sender, EventArgs e)
{
... other code ---
mailInboxItems = inboxFolder.Items;
mailInboxItems.ItemAdd += mailInboxItems_ItemAdd;
}
private void mailInboxItems_ItemAdd(object item)
{
Outlook.MailItem emailMessage = (Outlook.MailItem)item; // cast error
ProcessEmail(emailMessage);
}
An exception is thrown when, of course, the item coming in is not of type Outlook.MailItem:
Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Outlook.MailItem'.
How can I check that the parameter "item" is of only a valid type, i.e. Outlook.MailItem to avoid any exceptions?
You can use the "is" and "as" operators in C#. See How to: Programmatically Determine the Current Outlook Item for more information.
Also the Outlook object model provides the MessageClass property - a string representing the message class for the Outlook item. Under the hood the message class is used to identify what inspector to use in Outlook for displaying the item.