How to use C# Conditional Operator ?:

Ok, so I’ve been doing a lot of work with the DataTable in my code recently and one thing I found myself doing a lot of validation to check that a value is not NULL before trying to use it. I did this because I would get an error if the value in the column was NULL but I was trying to assign it to a variable.

I’ll show examples using the following data and we’ll call the DataTable dtUsers:

[table]
ID,Name, PostCode, TelNo, MobNo
1,Ross, ED4 9KL, 01234 654987, NULL
2,John, NULL, 01238 765253, 07979876123
[/table]

E.g. Long winded validation

foreach(DataRow r in dtUsers)
{
    if(r["ID"] == DBNull.Value)
        id = 0;
    else
        id = (int)r["ID"];

    if(r["Name"] == DBNull.Value)
        name = "";
    else
        name = r["Name"].ToString(); 
}

You can see here that I am trying to check that each column in the table has a value before trying to assign it but this is obviously a long way to achieve this. We can do the same thing in less lines of code using a Conditional operator “? :”

E.g. Using the conditional operator

foreach(DataRow r in dtUsers)
{
    id = r["ID"] == DBNull.Value ? 0 : (int)r["ID"];
    name = r["Name"] == DBNull.Value ? "" : r["Name"].ToString();
}

So what the conditional operator does, is it will first of all check a condition(true or false) and give the first value if true OR the second value if false. To put simply, an IF ELSE statement. In this case, it is basically saying

IF r[“ID”] is NULL THEN (?) give me the value 0 ELSE (:) give me the value of r[“ID”].

MSDN explain it like this.

condition ? first_expression : second_expression;

One other thing we can do to make sure we don’t have to validate on the code side is use the validation in our SQL queries which fill the data tables. If you look at a previous article I wrote about SQL COALESCE and ISNULL this will help us guarantee there is no DBNULL value in the column and it will always give us some value we can use.

I hope this is useful for some people. I find myself using it a lot when I know a column in the database tends to have a lot of null values. I should probably use it all the time but hey! Any questions, let me know.

Leave a Reply