Search code examples
c#exchangewebservices

Cannot Implicity Convert Type in findResults.NextPageOffset


I am working on the code to retrieve Exchange email messages by batches of 100.

SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults;
ItemView view = new ItemView(100);
int inboxCount = 1;
do
{
    findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
    foreach (var item in findResults.Items)
    {
        Console.WriteLine(inboxCount + ". " + item.Subject);
        inboxCount++;
    }

    //error below
    view.Offset = findResults.NextPageOffset;
}
while (findResults.MoreAvailable);

However, I encountered an error on findResults.NextPageOffset;, of the following:

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

Any help will be appreciated.


Solution

  • Just use Value, which will give you the int from the nullable int

    view.Offset = findResults.NextPageOffset.Value;
    

    However there is a chance it's null, what do you do then? Well, that's up to you.

    if(!findResults.NextPageOffset.HasValue)
       throw new InvalidOperationException("Oh dear...");
    

    Further Reading

    Nullable types (C# Programming Guide)

    Use the Nullable.HasValue and Nullable.Value readonly properties to test for null and retrieve the value, as shown in the following example: if (x.HasValue) y = x.Value;