1

In my VB.NET class I have some code like this:

Public Class barClass

Private Function foo(data as string)
    msgbox("Data is a string: " & data)
End Function

Private Function foo(data as integer)
    msgbox("Data is an integer: " & data
End Function

End Class

Which obviously lets you pass foo a string or integer.

I figured I could do the same for events, so I try:

Public Event FooRaised(data as string)
Public Event FooRaised(data as integer)

Which I assume would let me raise the event by passing it whatever data I get from foo but I get an error, saying I can't do that (that FooRaised has already been declared).

How do I achieve this?

OneFineDay
  • 9,004
  • 3
  • 26
  • 37
Grayda
  • 1,870
  • 2
  • 25
  • 43

1 Answers1

1

Declare a single event using an Object parameter, then check the type to process it:

Public Class Form1

  Public Event Foo(o As Object)

  Sub FooHandler(o As Object) Handles Me.Foo
    If o.GetType Is GetType(Integer) Then
      Dim i As Integer = DirectCast(o, Integer)
      i += 1 'add one to the integer value'
      MsgBox(i.ToString)
    ElseIf o.GetType Is GetType(String) Then
      Dim s As String = DirectCast(o, String)
      s &= "!!" 'append exclamation marks'
      MsgBox(s)
    End If
  End Sub

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    RaiseEvent Foo(21)
    RaiseEvent Foo("a string value")
  End Sub
End Class
SSS
  • 4,807
  • 1
  • 23
  • 44
  • If it isn't obvious, I added one and appended exclamation marks to show how to convert the Object back into the original variable type and use the variable. – SSS Jun 06 '14 at 11:43
  • A sub with an object type was where I was heading next, but I wasn't sure if there was a better way to go about it. Thanks for the answer! – Grayda Jun 14 '14 at 08:16