I have a bunch of ViewModel classes, Q001ViewModel, Q002ViewModel, …, QnnnViewModel. These all inherit from VMBase.
I also have a set of Subs ShowQnnn, ShowQnnn, …, ShowQnnn. An example is:
Private Sub ShowQ001()
Dim workspace As Q001ViewModel = _
CType(Me.Workspaces.FirstOrDefault(Function(vm) vm.GetType() Is GetType(Q001ViewModel)), Q001ViewModel)
If workspace Is Nothing Then
workspace = New Q001ViewModel(_dbc)
Me.Workspaces.Add(workspace)
End If
Me.SetActiveWorkspace(workspace)
End Sub
Workspaces is an ObservableCollection of VMBase.
The ShowQnnn procedures are used to display a ViewModel. The point is that a new QnnnViewModel will be added to the workspaces collection only if one of that type does not already exist.
Is there a way to turn then ShowQnnn procedures into one generic version?
Sorry but I don’t know VB.Net syntax enough regarding generics (feel free to edit my answer with the VB.Net version), so i’ll answer in C#.
If the constructors take different arguments the solution would look like :
Otherwise you could simplify even more using reflection :