3 ms·
Pattern matching can be quite powerful, e.g. in C# (which I wish was more indepth / more featured, it still feels a bit immature :( ) ``` switch(foo)
by LandR 9y ago
Pattern matching can be quite powerful, e.g. in C# (which I wish was more indepth / more featured, it still feels a bit immature :( )
```
switch(foo)
{
case TextBox t:
Console.Writeline(t.Text);
break;
case TextBox when t.Text = "Bob":
Console.WriteLine("Hello Bob");
break;
case Combobox c:
Console.WriteLine($"{c.SelectedItem}");
break;
case null:
Console.WriteLine("Ooops, null!");
break;
case int i when i == 5:
Console.WriteLine("got an int, and it was 5!");
break;
case default:
// handle the default case.
break;
}
```
IN languages like F#, pattern matching can compile time check you have covered all bases as well.
e.g, this won't build
````
type VariableResult =
| E of string
| V of string
let result = V "variable"
match result with
| E e -> printf "was error"
```
As i haven't told it how to handle the V case for that discriminated union. So you get nice compile time checking.
Ugh, how do you format code?
- masklinn 9y ago> Pattern matching can be quite powerful, e.g. in C# (which I wish was more indepth / more featured, it still feels a bit immature :( ) C# doesn't really deserve the name of pattern matching, just a type-based switch (with guards), you can't match on values let alone destructure them. > Ugh, how do you format code? 4 spaces indent.