Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/csharp/language-reference/operators/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ You can also add a run-time type check and a variable declaration to a property

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

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`.

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

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:

:::code language="csharp" source="snippets/patterns/PropertyPattern.cs" id="RecursivePropertyPattern":::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,27 @@ public static class PropertyPattern
public static void Examples()
{
WithTypeCheck();

// <EmptyPropertyPattern>
if (GetSomeNullableStringValue() is { } nonNullValue) // Empty property pattern with variable creation
{
Console.WriteLine("NotNull:" + nonNullValue);
}
else
{
nonNullValue = "NullFallback"; // we can access the variable here.
Console.WriteLine("it was null, here's the fallback: " + nonNullValue);
}
// </EmptyPropertyPattern>

}

private static string? GetSomeNullableStringValue()
{
// Simulate getting a nullable string value.
return DateTime.Now.Ticks % 2 == 0 ? "Hello, World!" : null;
}

// <BasicExample>
static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 };
// </BasicExample>
Expand Down
Loading