Home > database >  C# pattern matching with manipulated value of property
C# pattern matching with manipulated value of property

Time:10-07

Let's say I have a class

public class Foo
{
  public int Bar { get; set; }
  
  public string Baz { get; set; }
}

And I initialize this in a variable.

var foo = new Foo
{
  Bar = 123,
  Baz = "123"
};

Is it possible to pattern match this with the value manipulated?

Because I can do:

if (test is { Bar: >= 100 })
{
  // do
}

Is it possible to achieve this?

if (test is { Bar: >= 100, Baz: value.Length > 5 })
{
  // do
}

Above syntax is invalid.

CodePudding user response:

Nested property pattern {Length: > 5} should do the trick:

if (foo is { Bar: >= 100, Baz: {Length: > 5}})
{
    // do
}
  • Related