15 October 2014

FirstOrDefault() method, when it will return null

Few days back me and one of my friend were looking at a peice of code written in C# language. A line of code which was using FirstOrDefault() extension method for IEnumerable got my attention and we ended up in argument. The code was something like below.

public class Student
{
  public string FirstName;
  public string LastName;
  public string USN;
}

using System.Linq;
class Program
{
   static void Main(string[] args)
   {
    /*line 1*/
    List<Student> studentList = new List<Student>();

    /*line 2*/
    Student student = studentList.FirstOrDefault();

    /*line 3*/string name = student.FirstName;
    Console.Read();
   }
}

The code in the line 3 code got the attention and I said NullReferenceException will be thrown as Student being reference type whose default value will be null. For this my friend said NO, FirstOrDefault() will get the empty instance value which will not be null, so there will be no exception. To prove him wrong I had to execute the above C# code and show the below exception.

FirstOrDefault extension method and when it will return null

The method FirstOrDefault<TSource> will return the default of TSource when IEnumerable collection is empty. Here TSource can either be a value type or reference type.

  • If TSource is a reference type (e.g, Class), then its default value is null.
  • If TSource is a value type then it will return the default value which is not null. F.g, if TSource is a integer then default value will be 0.

To verify the default value you can use default(TSource) construct as shown below.

// Will print nothing, as default value of 
// reference type Student is null.
Console.WriteLine(default(Student)); 

// Will print 0
Console.WriteLine(default(int));

No comments:

Post a Comment