V
V
Vlad2018-12-25 09:09:49
C++ / C#
Vlad, 2018-12-25 09:09:49

Generic inheritance, how to do it right?

I tried to make a fairly simple example: two classes Foo and Boo "depend" on each other.

public class Foo<T, U> where T : Boo<U, T> where U : Foo<T, U>
    {
        protected readonly T _some;
        public Foo(T some)
        {
            _some = some;
        }
    }

    public class Boo<T, U> where T : Foo<U, T> where U : Boo<T, U>
    {
        protected readonly T _some;
        public Boo(T some)
        {
            _some = some;
        }
    }

each of the classes has classes-heirs
public class Too : Foo<Roo, Too>
    {
        public Too(Roo a) : base(a)
        {

        }
    }

    public class Roo : Boo<Too, Roo>
    {
        public Roo(Too b) : base(b)
        {
        }
    }

Is there a syntactic option to not specify itself in the parent ? I got to this game myself, studying generic types. To what extent is this design generally acceptable and viable? What are the practices? public class Roo : Boo< Too, Roo >

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2018-12-25
@Dywar

It’s even difficult to read, you get confused who depends on whom.
I've never seen anything like this, especially in production, and I hope I won't :)
There is a free report on generics from Jeffrey Rechter - https://youtu.be/H9mP0Ad3TtA?t=4666
Day 1, Hall 1, report 1.
He will tell you how they appeared and why.
In general, the generic is useful for defining templates and avoiding "packaging".

V
Vasily Bannikov, 2021-05-17
@vabka

Is there a syntactic option to not specify itself in the parent public class Roo : Boo< Too, Roo >?

No.
I got to this game myself, studying generic types. To what extent is this design generally acceptable and viable? What are the practices?

Sometimes this is used.
There is another interesting approach - it is called Fluent generics
. It looks something like this:
public class List : BaseAsyncEndpoint
    .WithRequest<AuthorListRequest>
    .WithResponse<IList<AuthorListResult>>
{
// ...
}

Here is a video about it: https://www.youtube.com/watch?v=hKiuj0huEI4&ab_cha...
Do not listen to MrDywar Pichugin
In general, a generic is useful for defining templates and avoiding "packaging".

Generics can also be used to create tricky, strongly-typed DSLs, such as in FluentMigrator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question