C # 7 Pattern matching is not null

I would like to capture the first instance of the enumerable, and then perform some action on the found instance, if it exists ( != null). Is there a way to simplify this access using the C # 7 Matching Template?

Take the following starting point:

IEnumerable<Client> clients; /// = new List<Client> {new Client()};
Client myClient = clients.FirstOrDefault();
if (myClient != null)
{
    // do something with myClient
}

Can I combine the call FirstOrDefaultwith using if statementsomething like this:

if (clients.FirstOrDefault() is null myClient)
{
    // do something with myClient
}

I do not see such examples on MSDN pattern matching or elsewhere in the stack overflow

+4
source share
2 answers

Absolutely you can do it. Used in my example string, but it will work the same with Client.

void Main()
{
    IList<string> list = new List<string>();

    if (list.FirstOrDefault() is string s1) 
    {
        Console.WriteLine("This won't print as the result is null, " +
                          "which doesn't match string");
    }

    list.Add("Hi!");

    if (list.FirstOrDefault() is string s2)
    {
        Console.WriteLine("This will print as the result is a string: " + s2);
    }
}
+4
source

RB NULL.

var client = clients.FirstOrDefault();
var implement = client?.PerformImplementation();

, . , .

+2

Source: https://habr.com/ru/post/1696132/


All Articles