The Person The Person - 3 years ago 62
C# Question

Error in conditional operator

I have this code which is working fine

if (dt.Rows.Count < 0)
{
DataRow row = dt.NewRow();

foreach (DataColumn column in dt.Columns)
{
if (column.ColumnName == "CreatedDate")
{
row[column] = DateTime.MinValue;
}
else
{
row[column] = 0;
}
}

dt.Rows.Add(row);

DataColumn col = new DataColumn("Status", typeof(string));
col.DefaultValue = "0";
dt.Columns.Add(col);
}

return dt;


This
DataTable
has these columns with mentioned datatype:


  • Id: Int

  • full_name: string

  • user_name: string

  • password: string

  • user_email: string

  • role: string

  • CreatedDate: Datetime



This code I am using in a web api controller. It returns data from a SQL query in json format

But if the
DataTable
is empty, then to prevent returning an empty array in json, I'm using this code; in case of empty
DataTable
, it will return zero in every field.

Now I am converting this code in one line (ternary operator) as follows:

DataRow row = dt.NewRow();

foreach (DataColumn column in dt.Columns)
{
row[column] = (column.ColumnName == "CreatedDate") ? DateTime.MinValue : 0;
}

dt.Rows.Add(row);

DataColumn col = new DataColumn("Status", typeof(string));
col.DefaultValue = "0";
dt.Columns.Add(col);

return dt;


I also tried these two approaches:

row[column] = (column.DataType == DateTime) ? DateTime.MinValue : 0;


and

column.ColumnName == "CreatedDate" ? (row[column] = DateTime.MinValue) : (row[column] = 0);


But they do not work

Error is:


Type of conditional expression can not be determined because there is no implicit conversion between System.DatTime and int


How to solve it?

Answer Source

The ternary operator ?: must return values of the same type (or where the second can be implicitly converted to the first).

Yours is trying to return either a DateTime (first) or int (second) and thus a conversion doesn't exist.

You need to do it in one of number of ways.

Code it with an if (as you have already done):

    if (column.ColumnName == "CreatedDate")
    {
        row[column] = DateTime.MinValue;
    }
    else
    {
        row[column] = 0;
    }

Since row[column] is of type object you can cast the DateTime to object:

    row[column] = (column.ColumnName == "CreatedDate") ? (object)DateTime.MinValue : 0;

Or, if you want to map multiple columns, do something like this:

Dictionary<string, object> defaults = new Dictionary<string, object>()
{
    { "CreatedDate", DateTime.MinValue },
    { "full_name", "n/a" },
    { "Id", default(int) },
};

foreach (DataColumn column in dt.Columns)
{
    row[column] = defaults.ContainsKey(column.ColumnName) ? defaults[column.ColumnName] : 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download