Why can't closed classes be typical type constraints?

I just wanted to know why closed classes cannot be common types of constraints?

Suppose I have a simple code snippet in C # as below

public sealed class Base { public Base() { } } public class Derived<T> where T : Base { public Derived() { } } 

When I create Derivedclass, I get "Base" is not a valid constraint. The type used as a constraint must be an interface, a non-printable class, or a type parameter.

+6
generics c #
source share
4 answers

Because then it makes no sense to be generic. T can only be Base , so you can also make it not common to start with.

Why do you want Derived be shared? Why do you want a type called Base (meaning it must be a base type) to be sealed?

+10
source share

Because T will never have child classes! There is no point in having such a generic character.

+2
source share

The compiler does not want to have problems creating something in common, if only one class can it ever be. Note that you can use a private class as a general constraint if the private class is passed as a type parameter. For example, if you have a class

  Class Foo (Of T, U As T)

you can create an instance of this class, where both parameters of the type type are the same private type, because you can also create instances where the parameters of the type are of different types.

+1
source share

T can be nothing but Base . So, what's the point of making it general?

0
source share

All Articles