Skip to content

Instantly share code, notes, and snippets.

@EifelMono
Last active September 6, 2022 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EifelMono/ba65235952e0a2fb6eb9f2119464b98b to your computer and use it in GitHub Desktop.
Save EifelMono/ba65235952e0a2fb6eb9f2119464b98b to your computer and use it in GitHub Desktop.
Console.WriteLine("Anonymous pattern matching");
var text = "Hello";
var person = new PersonRecord("Andreas", "Klapperich", 11);
var output = new { Text = text, Person = person } switch
{
{ Text: { }, Person: null } content => $"{content.Text} Unknown",
{ Text: { }, Person: { Name: "Andreas", LastName: "Klapperich", Age:> 0 } } content => $"{content.Text} ANDREAS KLAPPERICH",
{ Text: { }, Person: { Name: { }, LastName: { } } } content => $"{content.Text} {content.Person.Name} {content.Person.LastName}",
{ Text: { }, Person: { Name: null, LastName: { } } } content => $"{content.Text} ? {content.Person.LastName}",
{ Text: { }, Person: { Name: { }, LastName: null } } content => $"{content.Text} {content.Person.Name} ?",
{ Text: { }, Person: { } } content => $"{content.Text} everybody",
_ => "Something went wrong"
};
Console.WriteLine(output);
if (new { Text = text, Person = person } is { Text: "Hello", Person: { Name: "Andreas" } } ifContent)
{
Console.WriteLine(ifContent.Text);
Console.WriteLine(ifContent.Person.Name);
Console.WriteLine(ifContent.Person.LastName);
}
public record PersonRecord(string Name, string LastName, int Age);
@EifelMono
Copy link
Author

Anonymous Pattern matching

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment