0

I've been struggling with this for hours. Hopefully some of you vb.net gurus can help restore my sanity.

Scenario : I have an object (mqtt_client) which exposes connect / disconnect events that I need to trap and deal with. I need the object to be accessible from multiple subs / functions / modules in my code. so I'm declaring it Public within the enclosing class but outside a code block.

If I declare it outside the main sub like this :

Public mqtt_client = New MqttFactory().CreateManagedMqttClient
Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load

    ' Add Event Handlers for Connected and disconnected events
    AddHandler mqtt_client.Disconnected, AddressOf MQTTclient_disconnected_handler
    AddHandler mqtt_client.Connected, AddressOf MQTTclient_connected_handler

The addhandler fails as the events aren't exposed by mqtt_client and I'm not sure why.

However, If I do it this way :

 Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim mqtt_client = New MqttFactory().CreateManagedMqttClient
    ' Add Event Handlers for Connected and disconnected events
    AddHandler mqtt_client.Disconnected, AddressOf MQTTclient_disconnected_handler
    AddHandler mqtt_client.Connected, AddressOf MQTTclient_connected_handler

Then the addhandlers hook up fine, but then the object only has scope inside the sub and can't be access from a different module.

I can't put ALL of this code outside of the enclosing block as addhandler is a method and won't work there.

How should I be going about this? Any guidance would be gratefully received.

braX
  • 11,506
  • 5
  • 20
  • 33
CWDev
  • 19
  • 3

1 Answers1

0

Type inference only works for local variables, so while this gives mqtt_client the type of .CreateManagedMqttClient with Option Infer On:

Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim mqtt_client = New MqttFactory().CreateManagedMqttClient

this gives it the type Object:

Public mqtt_client = New MqttFactory().CreateManagedMqttClient

Public Sub Ruptela_Server(sender As Object, e As EventArgs) Handles MyBase.Load

Specify an explicit type for the field with As, and enable Option Explicit at the project level to avoid future problems. (Option Explicit and Option Strict should always be on for all source.)

Ry-
  • 218,210
  • 55
  • 464
  • 476