How can I convert a null value to string.empty before it has a chance to throw an exception?

B. Clay Shannon picture B. Clay Shannon · Sep 27, 2012 · Viewed 13.5k times · Source

I have the following code to enter a previous value into a DataGridView cell. If on row 0 and col 2 or greater, the val to the left, otherwise the value directly above:

private void dataGridViewPlatypi_CellEnter(object sender, DataGridViewCellEventArgs args)
{
    // TODO: Fails if it sees nothing in the previous cell
    string prevVal = string.Empty;
    if (args.RowIndex > 0)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.ToString();
    } else if (args.ColumnIndex > 1)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex-1].Value.ToString();
    }
    dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal;
}

This works great as long as there is a value to be seen and copied over. If the cell is blank, though, I get:

System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.

I'm guessing this is an opportunity to use the null coalesce operator, but (assuming my guess is good), just how do I implement that?

Answer

Nicholas Carey picture Nicholas Carey · Sep 27, 2012

Try something like this:

string s = SomeStringExpressionWhichMightBeNull() ?? "" ;

Easy!