0

I'm reviewing some code written by some ex employees and found this

public abstract class BaseClass<T, M> 
where T : BaseClass<T, M>, M
where M : IDisposable
{
    protected M PropertyName {get; private set}
    ...
    // T is never used in this class. Only M is used
}

Inherited classes are defined like this

public class InheritedClass : BaseClass<InhertiedClass, IFooInterface>, IFooInterface
{
   ...
}

IFooInterface : IDisposable {...}

My question is why does base class specify a generic type T that inherits from itself? If I remove this generic constraint then nothing changes, so I was wondering why is it there in the first place? Is there any benefit of specifying generic constraint like this that I'm unaware of?

Saad
  • 198
  • 2
  • 12
  • 2
    You may wish to read Eric Lippert's [Curiouser and curiouser](https://blogs.msdn.microsoft.com/ericlippert/2011/02/03/curiouser-and-curiouser/) to tell you *probably* what they were thinking of, but to know for sure, you would need to ask the ex employees. – Damien_The_Unbeliever Jul 25 '18 at 09:23
  • 1
    I'd say this is sort of an antipattern. Every time I saw this in code, I had problems. – Thomas Weller Jul 25 '18 at 09:23
  • 1
    Related: https://stackoverflow.com/questions/6618134/generic-class-with-self-referencing-type-constraint – Thomas Weller Jul 25 '18 at 09:23
  • It is not an unusual pattern, but one that is always easier to write than to read. Probably the easiest way to see it is by observing the compile errors you get when you remove the constraint. – Hans Passant Jul 25 '18 at 09:48
  • Do keep in mind that `T` **does not** inherit from itself. – Enigmativity Jul 25 '18 at 09:59
  • @Damien_The_Unbeliever It was a great read and I also see no point to use this pattern in our scenario. T is not even used in this case, a bad code smells indeed. – Saad Jul 25 '18 at 10:13
  • @HansPassant I see no compile time errors either as T is not being used. It seems unusual in this case. – Saad Jul 25 '18 at 10:14
  • 1
    @Enigmativity true, mix up of words there. What I tried to say was T is constrained to inherit from the same class that specifies the constraint. If that makes sense. – Saad Jul 25 '18 at 10:17

0 Answers0