Alex Kennedy
Alex Kennedy

Reputation: 35

Can if statements be combined with a variable assignment using pattern matching?

Example of the code that I am talking about:

if (sender is Panel p)
{
    if (p.Enabled == false)
    {
        AMButton.Checked = false;
        PMButton.Checked = false;
        currentSelectedTime = null;
    }
}

Is it possible to "do something more" with the variable p once its been cast in the first if statement thus combining the two statements?

Upvotes: 1

Views: 114

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

The accepted answer of

if (sender is Panel p && p.Enabled)

is correct and works right now.

In C# 8, pattern matching will (probably) be extended to allow property matching:

if (sender is Panel { Enabled: true } p)

This looks a little alien right now, but it's likely to be more and more idiomatic, particularly when matching multiple properties. The recursive patterns can be used to introduce more pattern variables too, and you don't need a pattern variable for the "outer" pattern. For example, suppose we only needed the Tag property from the panel, we could use:

if (sender is Panel { Enabled: true, Tag: var tag })
{
    // Use tag in here
}

Upvotes: 2

TheGeneral
TheGeneral

Reputation: 81493

Something such as if(sender is Panel p.Enabled). Combining the two if statements into one line like that. Does that make sense?

if(sender is Panel p && p.Enabled)

or to get real ugly

if(sender is Panel p && (p.Enabled = somethingElse) == ((someInt = anotherInt) == 5))

Upvotes: 4

Related Questions