willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

Rationale after the "literal" expression `where T : class` in C#

In C#, one is allowed to write:

public class Foo<T> where T : class {

}

And according to the C# specifications, this means that:

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

Some are of the opinion that the literal statement T : class is confusing, one could see it as.

The type argument must be a class type. So interfaces and delegates are not allowed. (wrong)

Where for instances interfaces and delegates are not allowed. I'm wondering if the C# design team considered this and why they didn't introduce a constraint like:

where T : reference

(Or another keyword that is more precise). What was the rationale to use : class instead?

Upvotes: 0

Views: 143

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62012

They wanted to stick to a keyword that was already present in the language. Surely reference or referencetype would be more precise.

Similarly, it is called where T : struct, not valuetype (or nonnullablevaluetype), even if both structs and enums are value types that can be used for T in that case. Also note that the special struct Nullable<> is not allowed if the constraint where T : struct was used.

Upvotes: 1

Ani
Ani

Reputation: 10916

where T: class

reads

where T: <reference type>

I'm not sure why it was called class, though. Someone who was sitting through the language team's meetings on that one might have to chime in.

Upvotes: 1

Related Questions