KyleMit
KyleMit

Reputation: 29839

C#7 Pattern Matching value Is Not Null

I'd like to grab the first instance of an enumerable and then perform some actions on that found instance if it exists (!= null). Is there a way to simplify that access with C#7 pattern Matching?

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 to FirstOrDefault with the if statement something like this:

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

I don't see any similar examples on MSDN Pattern Matching or elsewhere on Stack Overflow

Upvotes: 16

Views: 11739

Answers (2)

RB.
RB.

Reputation: 37182

Absolutely you can do that. My example uses string but it would work just 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);
    }
}

Upvotes: 21

Greg
Greg

Reputation: 11480

You could potentially use the following null propagation approach as an alternate to RB's answer.

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

This would automatically perform the null check though the syntax is attempting to utilize the code. A nice piece of syntactical sugar, condensing the code and still fairly expressive.

Upvotes: 3

Related Questions