Skip to content

Commit 4f8255d

Browse files
BillWagnerjskeet
authored andcommitted
Add example of compile-time error
Fixes dotnet#938 Add an example of a type pattern to demonstrate when a pattern generates a compile-time error.
1 parent defb608 commit 4f8255d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

standard/patterns.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,28 @@ A *declaration_pattern* and a *var_pattern* can result in the declaration of a l
2222

2323
Each pattern form defines the set of types for input values that the pattern may be applied to. A pattern `P` is *applicable to* a type `T` if `T` is among the types whose values the pattern may match. It is a compile-time error if a pattern `P` appears in a program to match a pattern input value ([§11.1](patterns.md#111-general)) of type `T` if `P` is not applicable to `T`.
2424

25+
> *Example*: The following example generates a compile-time error because the compile-time type of `v` is `Stream`. A variable of type `Stream` can never be an expression of type `string`:
26+
>
27+
> ```csharp
28+
> Stream v = OpenDataFile(); // compile-time type of 'v' is 'Stream'
29+
> if (v is string) // compile-time error
30+
> {
31+
> /* code assuming v is a string*/
32+
> }
33+
> ```
34+
>
35+
> However, the following doesn't generate a compile-time error because the compile-time type of `v` is `object`. A variable of type `object` could be an expression of type `string`:
36+
>
37+
> ```csharp
38+
> object v = OpenDataFile();
39+
> if (v is string s)
40+
> {
41+
> /* code assuming v is a string*/
42+
> }
43+
> ```
44+
>
45+
> *end example*
46+
2547
Each pattern form defines the set of values for which the pattern *matches* the value at runtime.
2648
2749
### 11.2.2 Declaration pattern

0 commit comments

Comments
 (0)