Kevin
Kevin

Reputation: 4848

Convert null field to zero before converting to int?

In my program, I'm looping through a datatable to get data from each field. One line of my code looks like this:

int LYSMKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);

Basically, I'm just taking the value that's in the cell and converting it to an int32. I run into a problem, though, when the data in the field is a null. I get an Invalid Cast error message about not being able to convert a "DBNull" to another type.

So, I know that I can just check the value of the field before I try to convert it by doing something like this:

if (resultsDT.Rows[currentRow]["LYSMKWh"] == null)
            {
                resultsDT.Rows[currentRow]["LYSMKWh"] = 0;
            }

But, is there a better way to do this? Is there something I can do "inline" while I'm trying to convert the value without having to resort to using the if ?

EDIT: I did try using this suggested method:

int LYSMKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"] ?? "0");

Unfortunately, I still received the Invalid Cast error message with regards to the DBNull type. It was suggested that I could have problems using the ?? operator if the types on either side were different.

Also, since I have complete control over the data that I'm building my datatable with, I changed it so that no null values would be written to any field. So, that pretty much negates the need to convert a null to an int32, in this case. Thanks for all the advice, everyone!

Upvotes: 15

Views: 75133

Answers (8)

Ram
Ram

Reputation: 45

You can use extension Method.

int LYSMKWh = resultsDT.Rows[currentRow]["LYSMKWh"].IfNullThenZero();

Create the below class

public static class Converter
{
    public static Int32 IfNullThenZero(this object value)
    {
        if (value == DBNull.Value)
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(value);
        }
    }
}

Upvotes: 2

Dennis Traub
Dennis Traub

Reputation: 51644

Check if it's DBNull.Value instead of null:

if (resultsDT.Rows[currentRow]["LYSMKWh"] == DBNull.Value)
{
    resultsDT.Rows[currentRow]["LYSMKWh"] = 0;
}

The ternary expression would work like this:

var LYSMKwhField = resultsDT.Rows[currentRow]["LYSMKWh"];
int LYSMKWh = LYSMKwhField != DBNull.Value ? Convert.ToInt32(rowData) : 0;

Upvotes: 1

CodeNaked
CodeNaked

Reputation: 41403

You can use a custom convert method:

public static int ConvertToInt32(object value, int defaultValue) {
    if (value == null)
        return defaultValue;
    return Convert.ToInt32(value);
}

You may need overloads that take other types, like string. You may have problems with the ?? operator if the types on either side are different.

Upvotes: 3

Adam Lear
Adam Lear

Reputation: 38778

You can replace it with a ternary operator:

var rowData = resultsDT.Rows[currentRow]["LYSMKWh"];
int LYSMKWh = rowData != null ? Convert.ToInt32(rowData) : 0;

Alternatively, the ?? operator could work:

int LYSMKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"] ?? 0);

But I think that's less readable.

Upvotes: 2

Zebi
Zebi

Reputation: 8882

You can use the ?? operator:

object x = null;

int i = (int)(x ?? 0)

Upvotes: 4

Random Dev
Random Dev

Reputation: 52290

use the ?? operator:

resultsDT.Rows[currentRow][...] ?? "0"

(expecting the field to be a string - if not change the "0")

Upvotes: 9

Yuck
Yuck

Reputation: 50855

You could do this:

var LYSMKWh =
    resultsDT.Rows[currentRow]["LYSMKWh"].Equals(DBNull.Value)
    ? 0
    : Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);

Upvotes: 14

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34790

You may consider using C#'s ?? operator, which checks a value for null and if it's null, assigns a default value to it.

Upvotes: 5

Related Questions