Search code examples
c#vb.netraiseevent

After conversion to VB, 'is an event and cannot be called directly.'


The code below is part of project to save exceptions globally. I have converted this from C# to VB with both SharpDevelop and with Telerik's Code Converter, and I get identical results.

Searching through Stackoverflow, I found this question: "'Why won't this C# convert to VB?', which address the same error I have and shows a simple answer, but doesn't show how to use it - at least so I would know what to change.

What I'm getting is an error on 'ONWRITETODATABASE'. The complete error is: 'Public Shared Event OnWriteToDatabase(type As String, text As String)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.

What do I change to make this work? (The caps are mine.)

Public Delegate Sub DatabaseWriteEventHandler(type As String, text As String)
Public Shared Event OnWriteToDatabase As DatabaseWriteEventHandler

Protected Function OnWriteToDatabase() As Boolean

    _logToDatabaseOK = False

    If ONWRITETODATABASE IsNot Nothing Then
        Try
            RaiseEvent OnWriteToDatabase(_exceptionType, _exceptionText)
            _logToDatabaseOK = True
        Catch ex As Exception
            _results.Add("LogToDatabase", ex.ToString())
        End Try
    Else
        _results.Add("LogToDatabase", "No subscriptions to OnWriteToDatabase event")
    End If

    Return _logToDatabaseOK

End Function

Solution

  • If you really want to include the "IsNot Nothing" check (and note Ben N's observation that you don't need it), you can reference the hidden VB event field:

    If OnWriteToDatabaseEvent IsNot Nothing Then 'the event followed by "Event"