HighMans HighMans - 6 months ago 21
Vb.net Question

Creating a class that inherits SerialPort

I have a class that inherits SerialPort and this class sets properties of a serial port as shown in the code below.
Public Class Ports

Inherits SerialPort

WithEvents port As New SerialPort()
Sub New()
With port
.BaudRate = 19200
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = False
.ReceivedBytesThreshold = 1
.NewLine = vbCr
.ReadTimeout = 10000
End With
End Sub
End Class


The issue with this is when I instantiate it,

Private WithEvents testPort As New Ports()


the properties of the serialport aren't transfered over and the default values are set.

Answer

The issue is because your not setting the instance for the object rather you are doing it for another variable inside that instance. As @the_lotus pointed out, remove the variable or the inheritance. I would recommend just removing the non needed variable WithEvents port As New SerialPort() and then use the instance...

Public Class Ports
    Inherits SerialPort

    Sub New()
        With Me
            .BaudRate = 19200
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
            .RtsEnable = False
            .ReceivedBytesThreshold = 1
            .NewLine = vbCr
            .ReadTimeout = 10000
        End With
    End Sub

End Class