Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No implicit conversion between int and null [duplicate]

I have a class and it has nullable properties like below;

public class Sample
{
   public int? ID { get; set; }
   public string SampleName { get; set; }
   public bool? Active { get; set; }
   public DateTime? Date { get; set; }
}

When i try to do something like below;

foreach (DataRow tableItem in table.Rows)
{
        Sample sample = new Sample()
        {
            ID = tableItem["ID"] != DBNull.Value ? Convert.ToInt32(tableItem["ID"].ToString()) : null,
            SampleName = tableItem["SampleName"] != DBNull.Value ? tableItem["SampleName"].ToString() : null,
            Active = tableItem["Active"] != DBNull.Value ? Convert.ToBoolean(tableItem["Active"].ToString()) : null,
            Date = tableItem["Date"] != DBNull.Value ? Convert.ToDateTime(tableItem["Date"].ToString()) : null,
        };

    data.Add(sample);
}

It gives error like "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''".

like image 721
thrashead Avatar asked May 05 '15 05:05

thrashead


1 Answers

null does not have any identifiable type - it just needs a little prodding to make it happy: Example is shown below.

int? number = true ? 5 : (int?)null;

Or you can do

int? number = true ? 5 : null as int?;
like image 179
BSG Avatar answered Oct 23 '22 00:10

BSG