Mr.Pe
Mr.Pe

Reputation: 739

Avoid numerous casts in inheritance tree

This is a problem which seems super basic but I still can't find a way to clear it. When I have a simple inheritance like B and C inheriting from A

   A
   |
|-----|
B     C

Let's say these are interface like:

public interface A
{
    List<A> Children { get; }
}

My issue: When I got through B.Children I have to cast it to B every time I want to use its specifics. Is there a way to have a list of children without having to declare the children in the leaves of the inheritance tree?

Precision: A child is always of the same type as its parent (or sub-type). And the tree can go deeper. As an example, think about a UI system with objects, containers, controls, labels where a class has as children only things of the same type or sub-types of itself.


Here is my code. I have the top level as

public interface ITerm
{
    String text { get; }
}

Then, as offered by @Damien_The_Unbeliever

public interface ITerm<T> : ITerm where T : ITerm
{
    List<T> Children { get; }
}

public interface ITermControl : ITerm<ITermControl> { ... }

public class TermControl : ITermControl { ... }

I am starting to think it is useless to have access to a List<ITerm> ITerm.Children as well as List<ITermControl> ITermControl.Children. That's what I was trying to explain.

Thanks

Upvotes: 3

Views: 103

Answers (1)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

You might try doing this:

public interface A<T> where T: A<T> {
    List<T> Children {get;}
}

Which Eric Lippert describes in his article Curiouser and Curiouser:

This is a C# variation on what's called the Curiously Recurring Template Pattern in C++, and I will leave it to my betters to explain its uses in that language. Essentially the pattern in C# is an attempt to enforce the usage of the CRTP.

And points out that it doesn't really enforce correct types throughout - so at best, it's a form of documentation rather than something that prevents bad things from happening.

Upvotes: 4

Related Questions