Search code examples
c#nullable

how fo feed a nullable parameter in a method?


I have a method that can accept nullable parameters because it is filled from a table with nullable columns.

private void test(int ID, int? value)
{}

When calling this method I need some way to feed it a nullable variable and there is my problem. I tried this :

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int?)row["value"]);
}

but it gives me a casting error

"specified cast is not valid"

So I tried this :

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int)row["value"] ?? DBnull.Value);
}  

and this :

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int)row["value"] ?? null);
}

but they both give me error

"Operator ?? cannot be applied to operands of type int and null

Last one I tried is this :

foreach (DataRow row in DataTable1.Rows)
{
    test((int)row["ID"], (int?)row["value"] ?? null);
}

this one compiles but gives runtime error

"specified cast is not valid"

So how can i do this ? The idea is that the parameter value is filled with either a value from the table or with null.


Solution

  • You can use the DataRow extension method Field which supports nullable types:

    foreach (DataRow row in DataTable1.Rows)
    {
        int id = row.Field<int>("ID");
        int? value = row.Field<int?>("value");
        test(id, value);
    }