Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sealed classes are not allowed to be generic type constraints?

Tags:

c#

generics

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.

like image 705
santosh singh Avatar asked Dec 10 '10 07:12

santosh singh


People also ask

Why we Cannot inherit sealed class?

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.

What are generic type constraints?

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.

Can generic classes be constrained?

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.

Can we inherit methods of sealed classes?

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.


2 Answers

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?

like image 71
Jon Skeet Avatar answered Sep 30 '22 04:09

Jon Skeet


Because T will never have child classes! There's no point to have such kind of generic.

like image 40
xandy Avatar answered Sep 30 '22 06:09

xandy