Skip to content

Commit 455d17b

Browse files
shethaaditAdit ShethBartoszKlonowskiBillWagner
authored
Refactored CS0077 Example with Modern C# Pattern Matching (#43108)
* Resolved issue 42861. * Update docs/csharp/misc/cs0077.md Thank you for the suggestion. Updating it. Co-authored-by: Bartosz Klonowski <[email protected]> * Update docs/csharp/misc/cs0077.md Co-authored-by: Bartosz Klonowski <[email protected]> * Update docs/csharp/misc/cs0077.md Co-authored-by: Bartosz Klonowski <[email protected]> * Update cs0077.md * Update docs/csharp/misc/cs0077.md --------- Co-authored-by: Adit Sheth <[email protected]> Co-authored-by: Bartosz Klonowski <[email protected]> Co-authored-by: Bill Wagner <[email protected]>
1 parent 6d63bec commit 455d17b

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

docs/csharp/misc/cs0077.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ ms.assetid: 55d3d290-d172-41a3-b326-ebf5a0a7e81f
1313
The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type).
1414

1515
The [as](../language-reference/operators/type-testing-and-cast.md#as-operator) operator was passed a [value type](../language-reference/builtin-types/value-types.md). Because `as` can return [null](../language-reference/keywords/null.md), it can only be passed a [reference type](../language-reference/keywords/reference-types.md) or a [nullable value type](../language-reference/builtin-types/nullable-value-types.md).
16+
17+
However, using [pattern matching](../fundamentals/functional/pattern-matching.md) with the [is](../language-reference/operators/is.md) operator, we can directly perform type checking and assignments in one step.
1618

1719
The following sample generates CS0077:
1820

@@ -39,10 +41,13 @@ class M
3941
o1 = new C();
4042
o2 = new S();
4143

42-
s = o2 as S;
43-
// CS0077, S is not a reference type.
44-
// Try the following line instead.
45-
// c = o1 as C;
44+
s = o2 as S; // CS0077, S is not a reference type
45+
46+
// Use pattern matching instead of as
47+
if (o2 is S sValue)
48+
{
49+
s = sValue;
50+
}
4651
}
4752
}
4853
```

0 commit comments

Comments
 (0)