summaryrefslogtreecommitdiffstats
path: root/docs/user-guide/06-interfaces-generics.md
diff options
context:
space:
mode:
authorkaizhangNV <149626564+kaizhangNV@users.noreply.github.com>2024-04-17 23:23:15 -0700
committerGitHub <noreply@github.com>2024-04-17 23:23:15 -0700
commitd3fd7470e6b71aa080415a3a7c207faebe21b00f (patch)
treede3b9c1642fbea11392bfaf170de31a6d80b2826 /docs/user-guide/06-interfaces-generics.md
parent5dd27a26da9b6b6191f3b1eba0f38f85714c1ae3 (diff)
Implement if(let ...) syntax (#3673) (#3958)
Diffstat (limited to 'docs/user-guide/06-interfaces-generics.md')
-rw-r--r--docs/user-guide/06-interfaces-generics.md58
1 files changed, 58 insertions, 0 deletions
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>(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<T>::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<MyImpl1> $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
-----------------------------