views:

60

answers:

1

Imagine that I have a generic base class like this:

public abstract class AnimalDTO<TA, TB>
{
    public static TB ToDTO(TA entity)
    {
        return ConvertToDTO<TB>(entity);
    }
}

The class is responsible for being able to convert a passed-in entity to a DTO.

I have a class that uses this generic class:

public class MammalDTO<Mammal, MammalDTO>
{
    // omitted stuff here
}

A user can now use MammalDTO.ToDTO(mammal) to convert a Mammal to a MammalDTO.

Now I want to derive off Mammal:

public class Koala<???, ???> : Mammal<???, ???>

How do I do this?

+1  A: 

One solution would be to makeMammalDTOan open but constrained generic type. You could then try to constrain the generic further and further as you go down the inheritance hierarchy, closing it at a leaf. It may also be suitable to use abstract classes as appropriate, but this is not a requirement of the pattern.

To be honest though, I don't really like the 'self-referencing generic' pattern; I find it quite confusing.

public abstract class Animal { }
public abstract  class Mammal : Animal { }
public sealed class Koala : Mammal { }

public abstract class AnimalDTO<TAnimal, TDTO> where TAnimal : Animal
{
    public abstract TDTO ConvertToDTO(TAnimal entity);       
}

public abstract class MammalDTO<TMammal, TMammalDTO> : AnimalDTO<TMammal, TMammalDTO>
    where TMammal : Mammal
    where TMammalDTO : MammalDTO<TMammal, TMammalDTO>{}

public sealed class KoalaDTO : MammalDTO<Koala, KoalaDTO>
{
    public override KoalaDTO ConvertToDTO(Koala entity)
    {
        throw new NotImplementedException();
    }
}
Ani
Thanks. I think I'll try to find another way to do it, since I don't like this pattern either.
Daniel T.