Michael Bayer
Michael Bayer

Reputation: 157

Refactor method into a generic method

I have this proper working method:

Public Shared Function Create(panelName As String, panelCaption As String) As ViewModelA
    Return ViewModelSource.Create(Function() New ViewModelA() With {
        .Name = panelName,
        .Caption = panelCaption
    })
End Function

which creates and returns an object of type ViewModelA with its properties Name and Caption.

(Note: ViewModelSource.Create is a method of a 3d party MVVM-Framework, that returns an instance of the given POCO class (here: ViewModelA)).

This method is needed by a couple of ViewModels and every ViewModel actually has its own method. This methods only differs in the type (ViewModelA, ViewModelB, ViewModelC ...).

What I want to achive is only one single generic method that returns an object of the type given as parameter - like the following fantasy code:

Public Shared Function Create(Of T)(panelName As String, panelCaption As String) As T
    Return ViewModelSource.Create(Function() New T With {
        .Name = panelName,
        .Caption = panelCaption
    })
End Function

and using the method like this:

Dim vmA As ViewModelA = Create(Of ViewModelA)("myName", "myCaption")

Upvotes: 0

Views: 36

Answers (1)

DWRoelands
DWRoelands

Reputation: 4940

It sounds like you're talking about an implementation of the factory pattern.

Upvotes: 0

Related Questions