mosquito87
mosquito87

Reputation: 4440

Call constructor in abstract class with generics

I have the following base class which is abstract:

public abstract class MasterDataViewModel<TPrimaryModel> : ViewModel
    where TPrimaryModel : TwoNames, new()
{
    ...
}

I have some derived classes like:

public class ConsignorViewModel : MasterDataViewModel<Consignor>
{
    protected override void Find()
    {           
        ...
        foreach (Consignor consignor in consignors)
        {
            ConsignorViewModel viewModel = new ConsignorViewModel(consignor, consignor.Address);
            SearchResults.Add(viewModel);
        }
        ...

    }
}

I would like to move the Find method to my base class. The problem is the constructor call which is not possible in my abstract class. It has to be something like this:

protected override void Find()
{         
    ...
    foreach (TPrimaryModel primaryModel in results)
    {
        MasterDataViewModel<TPrimaryModel> viewModel = new MasterDataViewModel(primaryModel, primaryModel.Address);
        SearchResults.Add(viewModel);
    }
    ...
}

It's not working as constructor calls in abstract classes are not allowed. Any other solution? I thought about another generic. Problem is that a new constraint cannot have any parameters so this doesn't work, too.

Upvotes: 1

Views: 705

Answers (2)

John
John

Reputation: 3702

Either create an abstract method in the base class "CreateViewModel" that you override in each model. Or use the Activator.CreateInstance method to create an instance of the this.GetType() subclass.

The first one is the cleanest. That way your class serves as a factory for itself.

Upvotes: 0

msporek
msporek

Reputation: 1197

This design of classes doesn't sound to be right if the Find() method inside the MasterDataViewModel / ConsignorViewModel class is creating the instance of the class. This seems like the Find() method should be a static helper class, but we don't see all the code of the Find() method so I cannot say it for sure. If not a static method, then the Find() functionality should be moved out to another helper class.

Upvotes: 2

Related Questions