Skip to content

Commit 0f60b26

Browse files
committed
Add notnull example
Fixes #1256
1 parent ba0673e commit 0f60b26

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

standard/classes.md

+33
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,39 @@ The ***not null*** constraint specifies that a type argument used for the type p
489489
490490
Because `notnull` is not a keyword, in *primary_constraint* the not null constraint is always syntactically ambiguous with *class_type*. For compatibility reasons, if a name lookup ([§12.8.4](expressions.md#1284-simple-names)) of the name `notnull` succeeds it is treated as a `class_type`. Otherwise it is treated as the not null constraint.
491491
492+
> *Example*: Consider the following:
493+
>
494+
> <!-- Example: {template:"standalone-lib-without-using", name:"TypeParameterConstraints0", expectedWarnings:["CS8714","CS8714","CS8631"], ignoredWarnings:["CS0168"]} -->
495+
> ```csharp
496+
> #nullable enable
497+
> public class C { }
498+
> public class A<T> where T : notnull { }
499+
> public class B1<T> where T : C { }
500+
> public class B2<T> where T : C? { }
501+
> class Test
502+
> {
503+
> static void M()
504+
> {
505+
> // nonnull constraint allows nonnullable struct type argument
506+
> A<int> x1;
507+
> // warning: nonnull constraint prohibits nullable struct type argument
508+
> A<int?> x2;
509+
> // nonnullconstraint allows nonnullable class type argument
510+
> A<C> x3;
511+
> // warning: nonnull constraint prohibits nullable class type argument
512+
> A<C?> x4;
513+
> // nonnullable base class requirement allows nonnullable class type argument
514+
> B1<C> x5;
515+
> // warning: nonnullable base class requirement prohibits nullable class type argument
516+
> B1<C?> x6;
517+
> // nullable base class requirement allows nonnullable class type argument
518+
> B2<C> x7;
519+
> // nullable base class requirement allows nullable class type argument
520+
> B2<C?> x8;
521+
> }
522+
> }
523+
> ```
524+
492525
The value type constraint specifies that a type argument used for the type parameter shall be a non-nullable value type. All non-nullable struct types, enum types, and type parameters having the value type constraint satisfy this constraint. Note that although classified as a value type, a nullable value type ([§8.3.12](types.md#8312-nullable-value-types)) does not satisfy the value type constraint. A type parameter having the value type constraint shall not also have the *constructor_constraint*, although it may be used as a type argument for another type parameter with a *constructor_constraint*.
493526
494527
> *Note*: The `System.Nullable<T>` type specifies the non-nullable value type constraint for `T`. Thus, recursively constructed types of the forms `T??` and `Nullable<Nullable<T>>` are prohibited. *end note*

0 commit comments

Comments
 (0)