Start here

Get started with an easy, short example that showcases the major features of Myra.


Go back

The match is only starting

This is how you use Myra.

The entry point to the Myra pattern matching machanism is the Match() extension method, that can be invoked from any type of object.

This method takes two parameters:

  • A Pattern<T>, that specifies the condition the matching object must verify.
  • An Action<T>, that will be executed if the condition is satisfied.

To create a pattern, use the Pattern.From() method, that takes a Func<T, bool> as a parameter:

var isEven = Pattern<int>.From(n => n % 2 is 0);

var isHusky = Pattern<Dog>.From(d => d is Husky);

A normal call to Match can look like this:

number.Match(isEven, n => Console.WriteLine($"{n} is even."));

// You can also inline the pattern
number.Match(Pattern<int>.From(n => n % 2 is 0), n => Console.WriteLine($"{n} is even."));
            

Rematch?

You can match several patterns against the same object.

To try a different pattern with an object, append another call to Match after the first one:

fluffy.Match(Pattern<Dog>.From(d => d is Husky), d => Console.WriteLine($"{d.Name} is truly fluffly."))
    .Match(Pattern<Dog>.From(d => d.Heads.Count > 1), d => Console.WriteLine($"{d.Name} is guarding the philosopher's stone."));
            

All the patterns will be checked, and any matching patterns will be executed. If you need a more advanced condition system, check the Advanced Logic guide.

You're all done!

Now you are ready to start using Myra, but there is still more to learn.


Go back