1

I was recently introduced to LINQ and got a sample how to search for error messages after executing a query against a database. The code looks like this:

        Dim errors As Object = From e In execution.Messages _
        Where e.MessageType = 120 Or e.MessageType = 110
        Select e.Message

        If errors IsNot Nothing Then
            For Each m As OperationMessage In errors
                LogToError("ExecutePackage->Error message: " & m.Message)
                sbError.AppendLine(m.Message)
            Next
        End If

Now, when I use Option strict ON I get an error on the "errors" object on this line:

For Each m As OperationMessage In errors

This is natural for me. So, I tried to change the code to this:

For Each m As OperationMessage In CType(errors, OperationMessageCollection)

Now, when I run it I get this error:

Unable to cast object of type 'WhereSelectEnumerableIterator`2[Microsoft.SqlServer.Management.IntegrationServices.OperationMessage,System.String]' to type 'Microsoft.SqlServer.Management.IntegrationServices.OperationMessageCollection'.

So, it seems to me that converting a LINQ query to another type at runtime does not work? What is the proper way of doing this and keeping Option strict ON?

serializer
  • 1,003
  • 2
  • 13
  • 27
  • 1
    Use Option Infer On and delete `As Object`. – Hans Passant Feb 17 '14 at 14:18
  • 1
    Use `Dim errors As IEnumerable(Of OperationMessage)` instead of `Object` or simply `Dim errors` without any type (same as `var` in C#) (**Edit** + `Option Infer` as mentioned by Hans Passant). – Tim Schmelter Feb 17 '14 at 14:19
  • @TimSchmelter - I get this error if I use the enumerable: System.InvalidCastException: Unable to cast object of type 'WhereSelectEnumerableIterator`2[Microsoft.SqlServer.Management.IntegrationServices.OperationMessage,System.String]' to type 'System.Collections.Generic.IEnumerable`1[Microsoft.SqlServer.Management.IntegrationServices.OperationMessage]'. – serializer Feb 18 '14 at 10:47

0 Answers0