TheSwamp

Code Red => .NET => ACAD with .NET8+ => Topic started by: kdub_nz on January 03, 2024, 06:11:46 PM

Title: Playing with: Simple Pattern matching in if statement
Post by: kdub_nz on January 03, 2024, 06:11:46 PM
Code - C#: [Select]
  1. global using static System.Console;  // just to save noise writing Console. prefix
  2.  
  3. // Add and remove the "" to change object o between string and int.
  4. object o = "3";
  5. int j = 4;
  6. if (o is int i)     // <= here be magic !
  7. {
  8.   WriteLine($"{i} x {j} = {i * j}");
  9. }
  10. else {WriteLine("o is not an int so it cannot multiply!"); }
  11.  
  12.  
Title: Re: Playing with: Simple Pattern matching in if statement
Post by: MickD on January 03, 2024, 07:33:37 PM
nice!  :-)
Title: Re: Playing with: Simple Pattern matching in if statement
Post by: kdub_nz on January 04, 2024, 01:04:02 AM
Yes Mick,

There has been a lot of nice stuff in the last 5 or 6 years that has been ignored because we were stuck with Framework 4.8

I just need to wrap my old brain around it all  :-D
Title: Re: Playing with: Simple Pattern matching in if statement
Post by: gile on January 04, 2024, 02:16:08 AM
Hi Kerry,

This was already available with C# 7 (and .NET Framework), see this topic (https://devblogs.microsoft.com/premier-developer/dissecting-the-pattern-matching-in-c-7/).
Title: Re: Playing with: Simple Pattern matching in if statement
Post by: gile on January 04, 2024, 03:42:37 AM
The same can been written with a switch statement (C# 7):
Code - C#: [Select]
  1. switch (o)
  2. {
  3.     case int i:
  4.         WriteLine($"{i} x {j} = {i * j}"); break;
  5.     default:
  6.         WriteLine("o is not an int so it cannot multiply!"); break;
  7. }

C# 8 introduced "switch expressions":
Code - C#: [Select]
  1. WriteLine(o switch
  2. {
  3.     int i => $"{i} x {j} = {i * j}",
  4.     _ => "o is not an int so it cannot multiply!"
  5. });

Title: Re: Playing with: Simple Pattern matching in if statement
Post by: kdub_nz on January 04, 2024, 04:21:37 AM
Thanks Gilles,
I missed that.



Title: Re: Playing with: Simple Pattern matching in if statement
Post by: gile on January 04, 2024, 05:31:24 PM
This way also works:
Code - C#: [Select]
  1. WriteLine(
  2.     o is int i ?
  3.     $"{i} x {j} = {i * j}" :
  4.     "o is not an int so it cannot multiply!");