Goos van den Bekerom
Goos van den Bekerom

Reputation: 1493

C# - Access property in inheriting class

I'm trying to access a generic typed property in a child class. In the below example I recreated my problem. Is there a workaround for this problem, or is it simply not possible? Thanks in advance!

EDIT: It's not possible to declare the collection as A<Model> or A<T>.

public abstract class Model {
    public int Id { get; }
}

public interface I<T> where T: Model {
    ICollection<T> Results { get; }
}

public abstract class A { }

public class A<T> : A, I<T> where T : Model {
    public ICollection<T> Results { get; }
}

public class Example {

    A[] col;

    void AddSomeModels() {
        col = new A[] {
            new A<SomeModel>(),
            new A<SomeOtherModel>()
        }
    }

    void DoSomethingWithCollection() {
        foreach (var a in col) {
            // a.Results is not known at this point
            // is it possible to achieve this functionality?
        }
    }
}

Upvotes: 4

Views: 66

Answers (1)

InBetween
InBetween

Reputation: 32790

You can't do what you intend without some compromises.

First of all, you need to make your interface I<T> covariant in T:

public interface I<out T> where T : Model
{
    IEnumerable<T> Results { get; }
}

The first compromise is therefore that T can only be an output. ICollection<T> isn't covariant in T so you'd need to change the type of Results to IEnumerable<T>.

Once you do this, the following is type safe and therefore allowed:

public void DoSomethingWithCollecion()
{
    var genericCol = col.OfType<I<Model>>();

    foreach (var a in genericCol )
    {
        //a.Results is now accessible.
    }
}

Upvotes: 5

Related Questions