diff options
Diffstat (limited to 'docs/user-guide/06-interfaces-generics.md')
| -rw-r--r-- | docs/user-guide/06-interfaces-generics.md | 58 |
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 ----------------------------- |
