Search code examples
c#.netgenericstype-parametertype-constraints

Empty interface or empty base class to use as type parameter constraint


Suppose I have a generic class in C# whose declaration looks like this:

public abstract class DtoQuery<T> where T : class
{ }

Now, the type parameter is intended to always be a "Dto" class. I have a bunch of these, but the "problem" is that they have nothing in common. They all have just a bunch of (distinct) public properties and no methods.

Ideally I would like to make my DtoQuery<T> class accept only such "Dto" classes as its type parameter. So I would either need to create an empty interface IDto or an empty abstract class Dto.

Question: which one should I go with? Note: the Dto classes will never extend anything else or each other!

(P.S. for the curious: I promise I'm not building something extremely stupid and silly, this is utility functionality in a testing project and won't be used for production code).


Solution

  • Let's say you have (for whatever reason), a hierarchy that looks like this:

    public class Person { }
    public class Employee : Person { }
    public class Boss : Person { }
    

    Now imagine, that we don't want a Person to be treated as a DTO - we only want Employee and Boss to be DTOs.

    In this situation, it would be impossible to use an abstract class to denote a DTO, as you can only inherit from one parent in C#.

    That's an objective reason as to why using an interface is better. Subjectively, interfaces are also better because the purpose of an abstract class is to provide some functionality. Other than that, is has no benefit over an interface.

    The rule of thumb is: Always use an interface when you're unsure. Only use an abstract class if you need implementation.