I just wanted to know why sealed classes are not allowed to be generic type constraints?
Let's suppose i have a simple code snippet in c# as bellow
public sealed class Base
{
public Base() { }
}
public class Derived<T>
where T : Base
{
public Derived() { }
}
When i am instantiating the Derivedclass i am getting 'Base' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.
You cannot derive or extend any class from it. Sealed method is implemented so that no other class can overthrow it and implement its own method. The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that they can't attain a class from a sealed class.
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, this class cannot be inherited.
Because then there's no point in it being generic. T
could only be Base
, so you might as well make it a non-generic type to start with.
Why would you want Derived
to be generic here? Why would you want a type called Base
(implying that it should be a base type) to be sealed?
Because T will never have child classes! There's no point to have such kind of generic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With