Skip to content

Instantly share code, notes, and snippets.

@SergeyTeplyakov
Created October 19, 2017 03:08
Show Gist options
  • Save SergeyTeplyakov/03fc1978e64cabbc3b7c516426b28c5a to your computer and use it in GitHub Desktop.
Save SergeyTeplyakov/03fc1978e64cabbc3b7c516426b28c5a to your computer and use it in GitHub Desktop.
using System;
interface IBase {}
interface IFoo : IBase
{
int A {get;}
}
class Foo : IFoo
{
public int A {get;set;}
}
interface IBoo : IBase
{
int B {get;}
}
public class TestPatternMatching {
public void Sample() {
string Match1(int o)
{
switch(o)
{
case int n when n > 100: return "> 100";
case int n when n > 50: return "> 50";
case int n when n > 10: return "> 10";
default: return "";
}
}
var result1 = Match1(70);
int Match2(IBase o)
{
switch(o)
{
case IFoo f: return f.A;
case IBoo b: return b.B;
default: throw new Exception("Foo is not of type IFoo nor IBoo, buhuhu:(");
}
}
int result2 = Match2(new Foo(){A=5});
string Match3(object o)
{
switch(o)
{
case 5: return o.ToString();
case "10": return "10";
case Foo _: return "foo";
default: throw new Exception();
}
}
string result3 = Match3(5);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment