What is the difference between First() and FirstOrDefault()


Hi

Onetime i was giving interview then i got this question.Then i told both is used for same purpose. But it was not the exact answer.

In simple word, FirstOrDefault() will handle the exception but First() will not handle the exception.

First() and FirstOrDefault() are two extension methods of the Enumerable class.

So lets test with some example in asp.net

 protected void Page_Load(object sender, EventArgs e)
    {
      
        int[] number = { 1, 5, 6 };
        var num = number.Where(n => n > 10).FirstOrDefault();;
        Response.Write(num);

    }


Note: This code will not throws the exception. So if we have to handle the exception then we can use FirstOrDefault();.

Now lets test with First()

 protected void Page_Load(object sender, EventArgs e)
    {
      
        int[] number = { 1, 5, 6 };
        var num = number.Where(n => n > 10).First();
        Response.Write(num);

    }

Note: This code will throw the exception.

Advertisement

2 thoughts on “What is the difference between First() and FirstOrDefault()

  1. Jean Paul July 9, 2013 / 3:59 pm

    Your blog is nice Chandra!

    You are noting down each stuff you learn.. & they are helpful for others.. Great Job!

    • Chandra Dev July 9, 2013 / 5:36 pm

      Thank you sir. I m really happy to see your nice comment on my blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.