VB .NET DirectCast and Type Reflection
- by msarchet
The application that I am working on has a generic Parent Form called RSChild, that is used to perform some operations depending on whether or not the control that is contained within it is in a MdiTabManager or inside of its own modal form. Then the actual User Controls contained within Inherit from a Interface Called ObjectEdit (Objects that we allow to be edited). At a point in my code I am doing this.
Public Function doesTabExist(ByVal id As Integer, ByVal recordType As Enums.eRecordType) As Boolean
Dim alikePages As Object = (From tabs In DirectCast(Control.FromHandle(MainForm.SharedHandle), MainForm).XtraTabbedMdiManager1.Pages Where DirectCast(tabs.MdiChild, RSChild).RSObject.RecordType = recordType Select tabs)
For Each page As DevExpress.XtraTabbedMdi.XtraMdiTabPage In alikePages
Select Case recordType
Case Enums.eRecordType.Doctor
If id = DirectCast(castTabPageToRSChild(page).RSObject, UI.Doctor).ID Then
pageToActive(page)
Return True
End If
'rest of the cases so the case block is repeated 10 times'
End Function
And my castTabPageToRSChild(page) is a lambda function as Such
Dim castTabPageToRSChild As Func(Of DevExpress.XtraTabbedMdi.XtraMdiTabPage, RSChild) = Function(page) DirectCast(page.MdiChild, RSChild)
So my Question is, I have about 10 case statements, all because I can't seem to find a way to use reflection to get the underlying Type of the RSObject Object. So I have the whole If block repeated over and over. I tried doing castTabPageToRSChild(page)RSObject.GetType and using that in the DirectCast and I also tried creating another object that was separate from that and doing the same thing.
My code works as intended I'm just trying to see if there is a manner in which I didn't have a lot of replicated code. My vision would be to do something like
For Each page As XtraMdiTabPage In alikePages
If id = DirectCast(castTabPageToRSchild(page).RSObject, TypeOfThatObject).Id Then Return True
Next
However I have a feeling this is not possible due to the behavior of DirectCast.