Declaring a variable in the if condition for further testing in C#

Viewed 727

I've seen it done before in a c# tutorial but I can't seem to find it again.

Take this code for example:

public class Order
{
    public  OrderItem Item { get; set; }
}

public class OrderItem
{
    public string Name { get; set; }
}


public void SomeMethod(object obj)
{
    if(obj is Order && ((Order)obj).Item !=null)
    {
        Console.WriteLine(((Order)obj).Item.Name);
    }
}

The shorthand I'm looking for looks something like this

public void SomeMethod(object obj)
{
    if (myObj = obj is Order && myItem = myObj.Item != null)
    {
        Console.WriteLine(myItem.Name);
    }
}

I'm not able to find the correct syntax for that

1 Answers

You are looking for pattern matching.

With property patterns (C# 8.0) you can do something like this:

if (obj is Order { Item: { } } order)
{
    Console.WriteLine(order.Item.Name);
}

This will check that obj is an Order and it has non-null Item (via "empty" property pattern) and if both result in true will execute the code block using typed variable order.

Or even next:

if (obj is Order { Item: { } item })
{
    Console.WriteLine(item.Name);
}

Basically the same but will use item variable for non-null item.

Related