Is there a way to just require an object implement the members of an interface without requiring it to explicitly implement it in c#?

185 Views Asked by At

I am making a custom control similar to an ItemsControl so it has an Items property I want to be bindable to but in order for my control to update, the property must implement INotifyCollectionChanged. I'd like the user to be able to bind any object so long as it implements both INotifyCollectionChanged and IList.

While the simple solution is to create a new interface list like so

public interface INotifyCollectionChangedAndList : INotifyCollectionChanged, IList { }

and require it be inherited on their custom collection objects.

However, instead of doing this they should also be able to use the standard ObservableCollection<T> as well which does inherit both INotifyCollectionChanged and IList but it does not inherit INotifyCollectionChangedAndList and I don't really have control over that. Likewise if they use a different library with a type that they can't control that does implement the two interfaces it should still work.

So my question is if there a way, easy or otherwise (i.e. reflection) where I can specify any type used must implement all the requirements of two (or more) interfaces without the explicit SomeClass : INotifyCollectionChangedAndList?

EDIT

I believe the answer is no. So I'm gonna mark @benjamin answer as correct because although it might not be the best for control authors, it will in other cases be the closest thing to what I would otherwise like to achieve.

1

There are 1 best solutions below

3
benjamin On BEST ANSWER

Yes, there is. You don't need reflection. Just make your class generic and specify that whatever type parameter is passed must implement both interfaces:

    public class ItemsController<TModel, TItem> where TModel : INotifyPropertyChanged, IEnumerable<TItem>
    {
        public TModel Model { get; set; }
    }

TModel can be anything that implements both the interfaces you require, so you always know that your ItemsControllers will have a Model property of type TModel that implements INotifyPropertyChanged and also has an Items property of type IEnumerable<TItem>.