14

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 ''".

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
thrashead
  • 337
  • 1
  • 3
  • 16
  • You have empty data that can not convert to int – Peyman May 05 '15 at 05:48
  • For simple cases (where DBNull can be replaced by a default value) I wrote a extension method: public static int ToIntEx(this object value, int defaultvalue = 0) { int result = defaultvalue; if (value != null && value != DBNull.Value) { Int32.TryParse(value.ToString(), out result); } return result; } – Thomas Krojer May 05 '15 at 05:50

1 Answers1

57

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?;
BSG
  • 2,084
  • 14
  • 19
  • Did you solve this issue?. Please do not forget to upvote or accept the answer provided by stack overflow members. If the answer is incorrect or not useful you can also downvote the answer. – BSG May 13 '15 at 06:11
  • yes thank you so much. – thrashead Sep 02 '15 at 11:15