okieh
okieh

Reputation: 627

Generic class with two generic types

I have a generic class for "Selectable Items" which is useful for Lists. Now I want a selectable item to include a list of other selectable items. Here is my code:

public interface ISelectableItem<T>
{
    bool IsSelected { get; set; }
    bool IsVisible { get; set; }
    string DisplayName { get; set; }
    T Value { get; set; }
    ObservableCollection<ISelectableItem<T>> SubItems { get; }
}

For now the SubItems collection is of the same type as the SelectableItem itself.

Question is: how do I have to declare this interface so that SubItems is also ISelectableItem, but of type T2, not T?

Upvotes: 1

Views: 386

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156918

Add a second generic type, T2, to the type definition:

public interface ISelectableItem<T, T2>
{
    T Value { get; set; }
    ObservableCollection<ISelectableItem<T2>> SubItems { get; }
}

Plan B would be to deviate between the sub items and master items by adding a second interface layer:

public interface ISelectableItem<T, T2> : ISelectableItem<T>
{
    ObservableCollection<ISelectableItem<T2>> SubItems { get; }
}

public interface ISelectableItem<T>
{
    bool IsSelected { get; set; }
    bool IsVisible { get; set; }
    string DisplayName { get; set; }
    T Value { get; set; }
}

This would work for example:

public class A : ISelectableItem<string> { ... }

public class B : ISelectableItem<string, string> { ... }

B b = new B();
b.SubItems.Add(new A());

Or even:

b.SubItems.Add(new B());

Upvotes: 3

Related Questions