0

I am returning an integer list from a datacolumn. This particular column is (int,null). But I got an exception.

Specified cast is not valid.

Code:

public List <int> GetSortOrder(DataTable dt,string columnName)
{
    List<int> Orders = new List<int>();
    foreach (DataRow row in dt.Rows)
    {
        Orders.Add((int)row[columnName]);
    }
    return Orders;
}

What I want is if it is null, then forcing it as 0. Should I use nullable type int? or just simply using if ... else...?

slfan
  • 8,950
  • 115
  • 65
  • 78

5 Answers5

6
        Orders.Add((int)(row[columnName] ?? 0));
paul
  • 21,653
  • 1
  • 53
  • 54
3

The column actually stores DBNull.Value instead of usual C# null. That's why operator ?? is not working. To check if the column is null use row.IsNull method:

Orders.Add(row.IsNull(columnName) ? 0 : (int)row[columnName]);

Operator ?? doesn't work with DBNulls.

You may also want to check this link: Handle DBNull in C# for some efficient examples of converting DBNull-able int to int?

Community
  • 1
  • 1
Artemix
  • 2,113
  • 2
  • 23
  • 34
1

I would also use an int? I like the Field method:

int? myInt = row.Field<int?>(columnName);
Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48
0

I'd suggest int?:

Orders.Add(((int?)row[columnName]).GetValueOrDefault());

In my opinion, it keeps the intent and code clear and concise, which an if/else doesn't do quite as well. Using ?? 0 as the other answers have suggested is also good.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • The intent of the code is to return an integer that is defaulted to 0, according to the original question. I don't see how allowing a `null` value in the list improves clariry or intent - it would seem to contradict both. – Dan Puzey Aug 02 '12 at 14:29
0

That should work:

public List <int> GetSortOrder(DataTable dt,string columnName)
{
    List<int> Orders = new List<int>();
    int? nullableInt;
    foreach (DataRow row in dt.Rows)
    {
        nullableInt = (int)row[columnName];
        Orders.Add(nullableInt??0);
    }
    return Orders;
}
Jan
  • 2,168
  • 2
  • 19
  • 28
  • No, you'll still get an error when you try to cast a `null` value to `int`. You need to cast to `int?`. – Dan Puzey Aug 02 '12 at 14:32
  • I wasn't sure as I didn't actually try it with real data. But it does compile like that... – Jan Aug 02 '12 at 14:39
  • Of course it compiles, because row[columnName] is of type object. The exception is thrown at runtime. By the way both (int)row[columnName] and (int?)row[columnName] throw an exception when row[columnName] is DBNull.Value. – Artemix Aug 02 '12 at 19:31