From d3fd7470e6b71aa080415a3a7c207faebe21b00f Mon Sep 17 00:00:00 2001 From: kaizhangNV <149626564+kaizhangNV@users.noreply.github.com> Date: Wed, 17 Apr 2024 23:23:15 -0700 Subject: Implement if(let ...) syntax (#3673) (#3958) --- docs/user-guide/06-interfaces-generics.md | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) (limited to 'docs/user-guide/06-interfaces-generics.md') diff --git a/docs/user-guide/06-interfaces-generics.md b/docs/user-guide/06-interfaces-generics.md index ba543df56..cb6a5070e 100644 --- a/docs/user-guide/06-interfaces-generics.md +++ b/docs/user-guide/06-interfaces-generics.md @@ -677,6 +677,64 @@ T compute(T a1, T a2) // compute(3, 1) == 2 ``` +`as` operator can also be used in the `if` predicate to test if an object can be casted to a specific type, once the cast test is successful, +the object can be used in the `if` block as the casted type without the need to retrieve the `Optional::value` property: +```csharp +interface IFoo +{ + void foo(); +} + +struct MyImpl1 : IFoo +{ + void foo() { printf("MyImpl1");} +} + +struct MyImpl2 : IFoo +{ + void foo() { printf("MyImpl2");} +} + +struct MyImpl3 : IFoo +{ + void foo() { printf("MyImpl3");} +} + +void test(IFoo foo) +{ + // This syntax will be desugared to the following: + // { + // Optional $OptVar = foo as MyImpl1; + // if ($OptVar.hasValue) + // { + // MyImpl1 t = $OptVar.value; + // t.foo(); + // } + // else if ... + // } + if (let t = foo as MyImpl1) // t is of type MyImpl1 + { + t.foo(); + } + else if (let t = foo as MyImpl2) // t is of type MyImpl2 + { + t.foo(); + } + else + printf("fail"); +} + +void main() +{ + MyImpl1 v1; + test(v1); + + MyImpl2 v2; + test(v2); +} + +``` + Extensions to Interfaces ----------------------------- -- cgit v1.2.3