Search code examples
c#classgenericsgeneric-constraints

What exactly is a "Special Class"?


After failing to get something like the following to compile:

public class Gen<T> where T : System.Array
{
}

with the error

A constraint cannot be special class `System.Array'

I started wondering, what exactly is a "special class"?

People often seem to get the same kind of error when they specify System.Enum in a generic constraint. I got the same results with System.Object, System.Delegate, System.MulticastDelegate and System.ValueType too.

Are there more of them? I cannot find any info on "special classes" in C#.

Also, what is so special about those classes that we can't use them as a generic type constraint?


Solution

  • From the Roslyn source code, it looks like a list of hardcoded types in isValidConstraintType:

    switch (type.SpecialType)
    {
        case SpecialType.System_Object:
        case SpecialType.System_ValueType:
        case SpecialType.System_Enum:
        case SpecialType.System_Delegate:
        case SpecialType.System_MulticastDelegate:
        case SpecialType.System_Array:
            // "Constraint cannot be special class '{0}'"
            Error(diagnostics, ErrorCode.ERR_SpecialTypeAsBound, syntax, type);
            return false;
    }