3

I've recently found myself using a generics with constraint that a type should inherit from a specific base class, but now I've just realised that this is redundant and unnecessary because the following code:

public class SomeClass<T> where T: SomeBaseClass
{
   T SomeProperty{ get; set;}
}

can be replaced with:

public class SomeClass  
{
SomeBaseClass SomeProperty{ get; set;}
}

So what is the advantage of using the generics approach?

1
  • 1
    Fun: public abstract class LinkedList<T> where T: LinkedList { public T Next { get; set; } }
    – Joshua
    Dec 30 '21 at 23:45
11

If it would be only about classes, and only about one class, your argument could be valid: you could perfectly perform manually the type substitution in the code.

But you would hardwire the choice of the type in your code. Although in many case, it's not an issue, you'd force the use of SomeBaseClass interface when using SomeProperty. With generics, you can use all the features of the T class, for example:

SomeClass<SomeSpecializedClass> b; 
b.SomeProperty.specialMethod();   // you can use any of SomeSpecialized methods 
                                  // you're not limited to SomeBaseClass methods only

Moreover, the where clause is not necessarily about a base class. It could be about interfaces, and even multiple interfaces that must be satisfied at the same time. This is much more difficult and tedious to achieve with manual type substitution.

5

The primary advantage of the generics approach is for consumers of the class. If SomeBaseClass has two implementations, FooClass and BarClass, and we have a consumer that takes a SomeClass and needs SomeProperty to contain only FooClass with generics it can express that by taking a SomeClass<FooClass>. Without the generics there would be nothing stopping the consuming class being passed a SomeClass containing BarClass. The simplest examples of this are containers like List, where the list does not care what's in it, but it is extremely useful for code using lists to be able to express that a list will only ever contain a specific type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.