What does the "default" generic constraint do?

Viewed 843

The following code compiles, but it seems that Microsoft's docs don't mention this particular constraint type at all.

class TestGenericsBase<T1>
{
    public virtual void Method1<T>(T arg)
    {
    }
}

class TestGenerics : TestGenericsBase<object>
{
    public override void Method1<T>(T arg)
        where T : default // what does this do?
    {
    }
}

Any idea what does it do? The only clue I have so far is that it only works on methods.

1 Answers

This default constraint can be found in C#9 design proposal for nullable reference types. It was added to disambiguate between class in struct constraints in overriden or explicitly implemented methods for nullable generic parameters T?.

More details also can be found in the Unconstrained type parameter annotations proposal

To allow annotations for type parameters that are not constrained to reference types or value types, C#9 allows a new where T : default constraint.

These constraints and annotations are working within nullable contexts

Related