I most be missing something here,
see in the image i made of my debug session.

(items[i] is MailItem) is FALSE according the debugger, but still it enters the if statement.
What am I missing here ?
.

enter image description here

For reference, here is the full code of this method

private MailItem GetMailBySubject(DateTime dateReceived, string subject)
{
    MailItem Result = null;

    Microsoft.Office.Interop.Outlook.Application OutlookIns = new Microsoft.Office.Interop.Outlook.Application();
    Microsoft.Office.Interop.Outlook.NameSpace olNamespace = OutlookIns.GetNamespace("MAPI");
    MAPIFolder myInbox = olNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);


    Items items = myInbox.Items;
    int count = items.Count;
    MailItem mail = null;
    int i = 1; //DO NOT START ON 0

    while ((i < count) && (Result == null))
    {
        if (items[i] is MailItem)
        {
            mail = (MailItem)items[i];
            if ((mail.ReceivedTime.ToString("yyyyMMdd hh:mm:ss") == dateReceived.ToString("yyyyMMdd hh:mm:ss")) && (mail.Subject == subject))
            {
                Result = mail;
            }
        }
        i++;
    }

    return Result;
}

2 Answers

0
GuidoG On

I made a workaround using the link provided by Wai Ha Lee. I had to alter it though, because testing if an item is MailItem still behaved strangely.

So I copy the items first into a separate list, and make sure only items of type MailItem are in that list.
The only way I got this filtered is by using try...catch, I would still like a better way and I am still curious why the test if (items[i] is MailItem) behaves so strangely.

List<MailItem> ReceivedEmail = new List<MailItem>();
foreach (var testMail in items)
{
    try
    {
        ReceivedEmail.Add((MailItem)testMail);
    }
    catch (System.Exception ex)
    {
        ;
    }
}

After this I can use the list ReceivedEmail without the check on MailItem.

1
user10103607 On

This SO answer explains a bit about why you are seeing the IF condition getting passed even when the expression inside it is false. Apparently it's an issue with the debugger and multiple threads. Also, it suggests a workaround to prevent this issue by using lock. Hope it helps.