Kevin Meredith
Kevin Meredith

Reputation: 41909

FirstOrDefault Behavior with Int and Int?

I just read a SO post that explained that FirstOrDefault()'s return type will vary based on the value of the element being selected.

Example:

ICollection<String> list = new List<String>();
list.Add("bye");

int a = (from x in list where (x == "hi") select x.Length).FirstOrDefault(); 

In this example, a will be equal to 0 since the int default value is 0.

However, I can append .Cast<int?>() as per the already linked post in order to get null when the query returns 0 results.

int? a = (from x in list where ... x.Length).Cast<int?>().FirstOrDefault();

Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable int (int?) rather than a regular int?

If I understand correctly, using a int? when performing my first query will never result in a value of null.

Upvotes: 25

Views: 29475

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Why don't I get a compile-time error (or at least a warning) when, for my first example, I use a Nullable int rather than a regular int then? If I understand correctly, using a int? when performing my first query will never result in a value of null.

Your understanding is correct. However, the compiler does not interfere with your desire to declare variable a as nullable, because it is a "widening" conversion: even though the assignment from the LINQ query would never return a null, you may have other use for the same variable down below:

int? a = (from x in list where (x == "hi") select x.Length).FirstOrDefault();
// Do something with `a`, which will not be null
...
a = null;
if (someCondition) {
    a = someNotNullValue();
}
// Here, a may or may not be null
...

Upvotes: 20

Related Questions