Choub890
Choub890

Reputation: 1163

Verify that generic type implements a certain interface

I have the following interfaces:

public interface IView<TViewModel>
{
    TViewModel ViewModel { get; set; }
}

public interface IViewModel : INotifyPropertyChanged
{
}

I would like to make sure that the generic TViewModel is always a class that implements interface IViewModel. I could do the following:

public interface IView
{
    IViewModel ViewModel { get; set; }
}

But then I would not have access to all the properties and methods of the specific class of ViewModel.

How can I make sure that TViewModel is always a class that implements interface IViewModel?

Upvotes: 1

Views: 82

Answers (1)

imlokesh
imlokesh

Reputation: 2739

Specify a generic type constraint using the where clause.

public interface IView<TViewModel> where TViewModel : IViewModel
{
    TViewModel ViewModel { get; set; }
}

Upvotes: 4

Related Questions