Skip to content

Instantly share code, notes, and snippets.

@rollsch
Created August 1, 2017 02:51
Show Gist options
  • Save rollsch/e108b21b547b1888cf03e74b92ff6317 to your computer and use it in GitHub Desktop.
Save rollsch/e108b21b547b1888cf03e74b92ff6317 to your computer and use it in GitHub Desktop.
public static void SwitchPattern(object o)
{
switch (o)
{
case null:
Console.WriteLine("it's a constant pattern");
break;
case int i:
Console.WriteLine("it's an int");
break;
case Person p when p.FirstName.StartsWith("Ka"):
Console.WriteLine($"a Ka person {p.FirstName}");
break;
case Person p:
Console.WriteLine($"any other person {p.FirstName}");
break;
case var x:
Console.WriteLine($"it's a var pattern with the type {x?.GetType().Name} ");
break;
default:
break;
}
}
class Geometry();
class Triangle(int Width, int Height, int Base) : Geometry;
class Rectangle(int Width, int Height) : Geometry;
class Square(int width) : Geometry;
 
Geometry g = new Square(5);
switch (g)
{
    case Triangle(int Width, int Height, int Base):
        WriteLine($"{Width} {Height} {Base}");
        break;
    case Rectangle(int Width, int Height):
        WriteLine($"{Width} {Height}");
        break;
    case Square(int Width):
        WriteLine($"{Width}");
        break;
    default:
        WriteLine("<other>");
        break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment