One of my older posts on Stackoverflow listed some of what I consider to be flaws of C# and/or the .NET runtime. A recent reply to my post posed a good question about one of those flaws, which was that sealed classes should be allowed as type constraints. That seems like a sensible restriction for C# at first, but there are legitimate programs that it disallows.

I figured others would have run into this problem at some point, but a quick Google search didn't turn up much, so I will document the actual problem with this rule. Consider the following interface:

interface IFoo<T> { void Bar<U>(U bar) where U : T; }

The important part to notice here is the type constraint on the method, U : T. This means whatever T we specify for IFoo<T>, we should be able to list as a type constraint on the method Bar. Of course, if T is a sealed class, we cannot do this:

class Foo : IFoo<string> { public void Bar<U>(U bar) where U : string //ERROR: string is sealed! { } }

In this case, there's a workaround by allowing the compiler to infer the constraint by making the method private and visible only when coerced as an interface:

class Foo : IFoo<string> { void IFoo<string>.Bar<U>(U bar) { } }

But this means that you cannot call Bar on a Foo, you need to first cast it to an IFoo<string>, a completely unnecessary step.

In principle, every type constraint that the compiler can infer implicitly, we should be able to specify explicitly. This is clearly not the case here, and there is no reason for it. It's a purely an aesthetic restriction, not a correctness restriction, that the C# compiler devs took extra effort to implement.

And that is why we should allow sealed classes as type constraints.