Unable to cast System.Collections.Hashtable into type System.Collections.Generic.IDictionary

1.7k Views Asked by At

I am using Enterprise library 5.0, in fact, logging block. In some circumstances I handle below exception if connection with remote end point is not successfull:

Public Function Connect(ByVal sender As Socket) As Integer
    Dim result As Integer

    result = -1

    Try
        ' Connect the socket to the remote endpoint.
        sender.Connect(remoteEP)

        Logger.Write("Socket connected to remote endpoint {0}", _
                     sender.RemoteEndPoint.ToString())

        result = 0

    Catch ... another exception
    Catch ... another exception

    Catch ex As System.Net.Sockets.SocketException
        Using New Tracer(Common.LOGGING_SOCKETCONNECTIONERROR)
            Dim contextInfo As IDictionary = New Hashtable()
            contextInfo.Add("Additional Info (Stack Trace)", ex.StackTrace)

            Dim provider As DebugInformationProvider = New DebugInformationProvider()
            provider.PopulateDictionary(contextInfo)

            Dim logEntry As LogEntry = New LogEntry()
            logEntry.Categories.Add(Common.LOGGING_CRITICAL_ERRORS_CATEGORY)
            logEntry.Message = String.Format("An error occurred when attempting to access the socket: {0}", ex.Message)
            logEntry.ExtendedProperties = contextInfo

            Logger.Write(logEntry)
        End Using

  End Try

  Return result
End Function

When above exception is fired I get a conversion error in line:

provider.PopulateDictionary(contextInfo)

The conversion error is the following:

System.InvalidCastException was unhandled
  Message="Unable to cast object of type 'System.Collections.Hashtable' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."

What am I doing wrong?

1

There are 1 best solutions below

1
Willy On

Changing:

Dim contextInfo As IDictionary = New Hashtable()

by:

Dim contextInfo As IDictionary = New Dictionary(Of String, Object)

solves the problem.