C# Cannot implicitly convert type ‘int?’ to ‘int’

c++int

I have this query:

int cid =  (from c in dc.Cs
                where c.id == cid
                select c.clientid).FirstOrDefault();

return cid;

where c.clientid is nullable. But I receive this error:

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

Best Solution

Well, int? can be null while int can't. That's why the compiler complains: what should it assign to cid when the query returns null. You can try providing some default value in case of null:

int cid = (  from c in dc.Cs
            where c.id == cid
           select c.clientid)
  .FirstOrDefault() ?? 0; //TODO: put the right default value instead of 0

return cid;

which means return 0 in case of null (please, notice that you have two possibilities: 1. 1st item c.clientid is null; 2. dc.Cs when filtered is empty) and int?.Value otherwise