mosquito87
mosquito87

Reputation: 4440

Declare variable of a generic class

I have the following abstract class:

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

In another class I would like to declare a variable where a ViewModel could be saved to:

public class MainViewModel
{
    private ViewModel _currentViewModel;
}

This doesn't work as 2 parameters are required (because of the generic). I don't mind which ViewModel is saved to _currentViewModel, as long as the object inherits from the abstract class ViewModel.

This doesn't work as well:

public class MainViewModel
{
    #region Members
    private ViewModel<TwoNames> _currentViewModel;
    #endregion
}

Compiler error:

The type 'typename' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'parameter' in the generic type or method 'generic'

This is because TwoNames is an abstract class. Removing the "new()" constraint isn't a solution for me as I need to instantiate new objects of "TwoNames" in my abstract class (ViewModel). Any other idea?

Upvotes: 1

Views: 166

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292345

You need to create a non-generic base class:

public abstract class ViewModel : ObservableObject
{
    ...
}

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

And declare _currentViewModel as type ViewModel:

public class MainViewModel
{
    #region Members
    private ViewModel _currentViewModel;
    #endregion
}

Upvotes: 5

Related Questions