Question How to cast an object into its type?

Adagio

Well-known member
Joined
Dec 12, 2005
Messages
162
Programming Experience
Beginner
I'm having a bit of a problem here, hoping a nice person here can help me out

I have a method which receives an object as parameter. This object is always of a class I have created, it will never be something simple as string, integer, etc

In my simple example I have created a class called ClassThatWillBeUpdated that requires a type for some reason not shown in the example

VB.NET:
 Public Class ClassThatWillBeUpdated(Of T)

            Private _count As Integer = 0

            Public Property Count() As Integer
                Get
                    Return _count
                End Get
                Set(ByVal value As Integer)
                    _count = value
                End Set
            End Property

        End Class

public class MyAmazingClass

public myamazingvariable as string = "Bacon"

end class

I also have a module, where other methods in my app calls the function DoIt(of MyAmazingClass)()

The DoIt function will create an instance of ClassThatWillBeUpdated and return it. Before returning it, it will start a thread that uses this item

It is in the sub DoWorkWithoutT the interesting stuff happens. I need to find a way to get the type in the instance of ClassThatWillBeUpdated and cast that instance to a ClassThatWillBeUpdated instead of object
The end result here is that when the app calls the DoWork sub, it will from the applications point of view in this case look like it calls this:
DoIt(of MyAmazingClass)(item)

The item is ClassThatWillBeUpdated(of MyAmazingClass)
VB.NET:
Public Module ThreadingTestClasses       

        Public Function DoIt(Of T)() As ClassThatWillBeUpdated(Of T)
            Dim item As New ClassThatWillBeUpdated(Of T)

            StartThread(item)

            Return item
        End Function

        private Sub StartThread(ByVal item As Object)
            Dim thd As New Threading.Thread(AddressOf DoWorkWithoutT)
            thd.Start(item)
        End Sub

        private Sub DoWorkWithoutT(ByVal item As Object)
            

Dim castedItem as ClassThatWillBeUpdated = ctype(item, ClassThatWillBeUpdated)

dim T as type = castedItem.GetSubType

            DoWork(Of T)(item)
        End Sub

        private Sub DoWork(of T)(ByVal obj As ClassThatWillBeUpdated)

        End Sub

End Module


I'm not sure if I explained it well enough

Or maybe it would be possible to call the DoWork(of T)(item) directly when creating the thread, but as far as I know it's not possible to make a thread run a method that has (of T) as that is basically what I'm looking for

Needless to say, the above code would fail during compile as I have no idea how to do it, if it's even possible. I'm using .net framework 3.5
 
Back
Top