mercredi 3 novembre 2021

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

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

Aucun commentaire:

Enregistrer un commentaire