From 7349dc5cff49cf22c82eb912813e47f30cd7a757 Mon Sep 17 00:00:00 2001 From: Julius Ikkala Date: Sat, 28 Jun 2025 05:39:24 +0300 Subject: Minimal optional constraints (#7422) * Parse optional witness syntax * Allow failing optional constraint * Make `is` work with optional constraint * Allow using optional constraint in checked if statements * Fix tests * Make it work with structs * Fix MSVC build error * Disallow using `as` with optional constraints * Update test to match split is/as errors * Add tests * Fix uninitialized variables in tests * Add tests of incorrect uses & fix related bugs * Mention optional constraints in docs * format code * Fix type unification with NoneWitness * Fix formatting --------- Co-authored-by: slangbot <186143334+slangbot@users.noreply.github.com> Co-authored-by: Nathan V. Morrical --- docs/user-guide/06-interfaces-generics.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'docs/user-guide') diff --git a/docs/user-guide/06-interfaces-generics.md b/docs/user-guide/06-interfaces-generics.md index bb19fd776..7c957f685 100644 --- a/docs/user-guide/06-interfaces-generics.md +++ b/docs/user-guide/06-interfaces-generics.md @@ -144,6 +144,28 @@ struct MyType } ``` +Optional conformances can be expressed compactly using the `where optional` syntax: +```csharp +// Together, these two overloads... +int myGenericMethod(T arg) +{ +} + +int myGenericMethod(T arg) where T: IFoo +{ + arg.myMethod(1.0); +} + +// ... are equivalent to: +int myGenericMethod(T arg) where optional T: IFoo +{ + if (T is IFoo) + { + arg.myMethod(1.0); // OK in a block that checks for T: IFoo conformance. + } +} +``` + Supported Constructs in Interface Definitions ----------------------------------------------------- -- cgit v1.2.3