c# - FirstOrDefault Behavior with Int and Int? -


i read post explained firstordefault()'s return type vary based on value of element being selected.

example:

icollection<string> list = new list<string>(); list.add("bye");  int = (from x in list (x == "hi") select x.length).firstordefault();  

in example, a equal 0 since int default value 0.

however, can append .cast<int?>() per linked post in order null when query returns 0 results.

int? = (from x in list ... x.length).cast<int?>().firstordefault(); 

why don't compile-time error (or @ least warning) when, first example, use nullable int (int?) rather regular int?

if understand correctly, using int? when performing first query never result in value of null.

why don't compile-time error (or @ least warning) when, first example, use nullable int rather regular int then? if understand correctly, using int? when performing first query never result in value of null.

your understanding correct. however, compiler not interfere desire declare variable a nullable, because "widening" conversion: though assignment linq query never return null, may have other use same variable down below:

int? = (from x in list (x == "hi") select x.length).firstordefault(); // `a`, not null ... = null; if (somecondition) {     = somenotnullvalue(); } // here, may or may not null ... 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -