Skip to content

Instantly share code, notes, and snippets.

@kparkov
Last active September 27, 2020 23:27
Show Gist options
  • Save kparkov/09c2b8592a754e455cb14058762f44dc to your computer and use it in GitHub Desktop.
Save kparkov/09c2b8592a754e455cb14058762f44dc to your computer and use it in GitHub Desktop.
Assignment with switch and pattern matching #csharp
// By value
public enum Directions { Up, Down, Right, Left }
public enum Orientation { North, South, East, West }
Orientation orientation = direction switch
{
Directions.Up => Orientation.North,
Directions.Right => Orientation.East,
Directions.Down => Orientation.South,
Directions.Left => Orientation.West,
};
// Tuple value
public static string RockPaperScissors(string first, string second)
=> (first, second) switch
{
("rock", "paper") => "rock is covered by paper. Paper wins.",
("rock", "scissors") => "rock breaks scissors. Rock wins.",
("paper", "rock") => "paper covers rock. Paper wins.",
("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
("scissors", "rock") => "scissors is broken by rock. Rock wins.",
("scissors", "paper") => "scissors cuts paper. Scissors wins.",
(_, _) => "tie"
};
static Sector GetSector(Point point) => point switch
{
(0, 0) => Sector.Origin,
(2, _) => Sector.One,
var (x, y) when x > 0 && y > 0 => Sector.Two,
(1, var y) when y < 0 => Sector.Three,
_ => Sector.Unknown
};
// Complicated pattern
var x = strangeObject switch
{
var n when n is Square s && s.Side > 20 => 10,
var n when n is Circle c && c.Radius < 10 => 50,
_ => 0
};
var percent2 = price switch
{
var n when n >= 1000000 => 7f,
var n when n < 1000000 && n >= 900000 => 7.1f,
var n when n < 900000 && n >= 800000 => 7.2f,
_ => 0f // default value
};
// Deconstructable
public class Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y) => (X, Y) = (x, y);
public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}
public enum Quadrant
{
Unknown,
Origin,
One,
Two,
Three,
Four,
OnBorder
}
static Quadrant GetQuadrant(Point point) => point switch
{
(0, 0) => Quadrant.Origin,
var (x, y) when x > 0 && y > 0 => Quadrant.One,
var (x, y) when x < 0 && y > 0 => Quadrant.Two,
var (x, y) when x < 0 && y < 0 => Quadrant.Three,
var (x, y) when x > 0 && y < 0 => Quadrant.Four,
var (_, _) => Quadrant.OnBorder,
_ => Quadrant.Unknown
};
// Property pattern
object o = null;
var x = o switch
{
Car { Wheels: 3 } c => 6
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment