Search code examples
vb.nettypesdictionaryactivator

can i use narrow the Type i want to instantiate with Activator.CreateInstance


i got a large branch of Types that all got the same superclass and interface.

SuperClass: AbstractPackage Interface: IPackage

Types made with this.

Package0....Package723

i use Activator.CreateInstance to create a new instance of the packages, depending og the pattern, recieved from a UDP bytestream.

i got all the registered packages, in a New Dictionary(Of UInt32, Type).

the Uint32 is the package number (0-723) and the Type, is any of the Package0 - Package723 Types.

problem is, that Activator.CreateInstance creates any type of class, and i was wondering if i could narrow the scope Down?

i wanted to make the Dictionary(and Activator.CreateInstance) to only accept Packages. is that posable? thanks


Solution

  • i made a sligth change as Hans Passant pointed out for me, i might have been overthinking it.

    here is my new method ( i still need to add all the classes Again, but now i atleast know what types it generate.

    Public Function getPackage(ByVal bytes() As Byte) As APackage
            Dim pkgbytes As Byte() = New Byte(3) {}
            Dim o As Integer = 0
            For i As Integer = 8 To 11
                pkgbytes(o) = bytes(i)
                o += 1
            Next
    
            Dim package As APackage
    
            Dim iT As UInt32 = UByteChunk.getUInt32(pkgbytes)
            Select Case iT
                Case 0
                    '0 Acknowledge
                    package = New Package0(bytes)
                Case 152
                    '152 EventCall
                    package = New Package152(bytes)
                Case 157, 162, 165, 166
                    ' 157 Event Extension
                    ' 162 Event Delta Call
                    ' 165 
                    ' 166 Event Call Logging
                    package = New PackageCall(bytes)
                Case 174
                    '174 Event Targeting
                    package = New Package174(bytes)
                Case 187, 188
                    '187 SIP Rx
                    '188 SIP Tx
                    package = New PackageSIP(bytes)
                Case 93, 501, 502, 626
                    '93 Version
                    '501 Info
                    '502 Info 2
                    '626 License
                    package = New PackageText(bytes)
                Case 563
                    '563 System Endpoint
                    package = New Package563(bytes)
                Case Else
                    package = New PackageDefault(bytes)
            End Select
    
            Return package
        End Function