Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
KyleMit Avatar asked Apr 12 '18 22:04

KyleMit


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

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);
    }
}
like image 116
RB. Avatar answered Oct 08 '22 09:10

RB.