diff --git a/docs/csharp/language-reference/operators/patterns.md b/docs/csharp/language-reference/operators/patterns.md index 2299ac2518eff..0a9016daa7cc6 100644 --- a/docs/csharp/language-reference/operators/patterns.md +++ b/docs/csharp/language-reference/operators/patterns.md @@ -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"::: diff --git a/docs/csharp/language-reference/operators/snippets/patterns/PropertyPattern.cs b/docs/csharp/language-reference/operators/snippets/patterns/PropertyPattern.cs index 1c1be24b28836..c6ec2e031b1be 100644 --- a/docs/csharp/language-reference/operators/snippets/patterns/PropertyPattern.cs +++ b/docs/csharp/language-reference/operators/snippets/patterns/PropertyPattern.cs @@ -5,8 +5,27 @@ public static class PropertyPattern public static void Examples() { WithTypeCheck(); + + // + 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); + } + // + } + private static string? GetSomeNullableStringValue() + { + // Simulate getting a nullable string value. + return DateTime.Now.Ticks % 2 == 0 ? "Hello, World!" : null; + } + // static bool IsConferenceDay(DateTime date) => date is { Year: 2020, Month: 5, Day: 19 or 20 or 21 }; //