From 74e1cab13af635daebe4418d9de8494e7a0d8e5b Mon Sep 17 00:00:00 2001 From: Oli Sturm Date: Tue, 7 Nov 2023 22:25:28 +0000 Subject: [PATCH] feat: example for if (x is {} y) --- samples/CS8/Program.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/samples/CS8/Program.cs b/samples/CS8/Program.cs index 83a574f..0230fae 100644 --- a/samples/CS8/Program.cs +++ b/samples/CS8/Program.cs @@ -28,8 +28,10 @@ namespace CS8 { var (firstName, lastName) = personInfo; // firstName ist jetzt "Oli" und lastName ist "Sturm" - // Positional pattern (using a tuple - hence "tuple pattern" in this special case) - // Important: this works with any deconstructable type! Example coming up in CS9 sample. + // Positional pattern (using a tuple - hence "tuple pattern" in + // this particular case) + // Important: this works with any deconstructable type! Example + // for a class with a deconstructor included in CS9 sample. if (personInfo is ("Oli", var olisLastName)) Console.WriteLine($"Found Oli, his last name is {olisLastName}."); @@ -38,6 +40,18 @@ namespace CS8 { if (customer is { Address: { City: "Castle Douglas" } }) { Console.WriteLine("This customer lives around the corner"); } + + // Prize question: what is the point of this? + if (customer is { } c) { + // Work with c -- it is not null and matches the (empty, but + // extensible) property pattern. + // c is a copy of the object reference, which may be useful in multi- + // threading scenarios. + // Some people really like this pattern, but in most cases + // if (customer is not null) { ... } is just a good. + // (And btw, "is not null" is not really faster than "!= null" -- but + // it could be, and it expresses intention more explicitly. + } } } } \ No newline at end of file