Skip to content

Commit e64f857

Browse files
AdmiralSnyderBillWagnerCopilot
authored
Update patterns.md with empty property pattern details (#49385)
* Update patterns.md with empty property pattern details Clarify the behavior of the empty property pattern in C#. * Add code example for empty property pattern Added a code example demonstrating the use of an empty property pattern with variable creation in C#. * Move sample to snippets. Per conversation on #49385 * Update docs/csharp/language-reference/operators/patterns.md Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Bill Wagner <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 9721098 commit e64f857

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

docs/csharp/language-reference/operators/patterns.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,10 @@ You can also add a run-time type check and a variable declaration to a property
182182

183183
:::code language="csharp" source="snippets/patterns/PropertyPattern.cs" id="WithTypeCheck":::
184184

185+
This specifically means that the *empty* property pattern `is { }` matches everything non-null, and can be used instead of the `is not null` to create a variable: `somethingPossiblyNull is { } somethingDefinitelyNotNull`.
186+
187+
:::code language="csharp" source="snippets/patterns/PropertyPattern.cs" id="EmptyPropertyPattern":::
188+
185189
A property pattern is a recursive pattern. You can use any pattern as a nested pattern. Use a property pattern to match parts of data against nested patterns, as the following example shows:
186190

187191
:::code language="csharp" source="snippets/patterns/PropertyPattern.cs" id="RecursivePropertyPattern":::

docs/csharp/language-reference/operators/snippets/patterns/PropertyPattern.cs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,27 @@ public static class PropertyPattern
55
public static void Examples()
66
{
77
WithTypeCheck();
8+
9+
// <EmptyPropertyPattern>
10+
if (GetSomeNullableStringValue() is { } nonNullValue) // Empty property pattern with variable creation
11+
{
12+
Console.WriteLine("NotNull:" + nonNullValue);
13+
}
14+
else
15+
{
16+
nonNullValue = "NullFallback"; // we can access the variable here.
17+
Console.WriteLine("it was null, here's the fallback: " + nonNullValue);
18+
}
19+
// </EmptyPropertyPattern>
20+
821
}
922

23+
private static string? GetSomeNullableStringValue()
24+
{
25+
// Simulate getting a nullable string value.
26+
return DateTime.Now.Ticks % 2 == 0 ? "Hello, World!" : null;
27+
}
28+
1029
// <BasicExample>
1130
static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 };
1231
// </BasicExample>

0 commit comments

Comments
 (0)