Search code examples
c#maui

Try to check for null in dataset table column - C# .NET Maui


I'm converting a project from Xamarin.Android to .NET Maui and I'm getting warnings about

Possible Null Reference Assignment

when assigning the database table column to a property in my user class.

My code looks like this:

MyUser.Firstname = Utils.IsNull(MyDataSet.Tables[0].Rows[0]["Firstname"].ToString()) ? "" : MyDataSet.Tables[0].Rows[0]["Firstname"].ToString();

The function being called in the Utils class is:

    public static bool IsNull(object value)
    {
        if (value == System.DBNull.Value)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Even though I'm checking if the data column is null, I'm still getting the warning. I'd like to code this so that I don't get that warning and nothing I've tried thus far has done that.


Solution

  • This value MyDataSet.Tables[0].rows[0]["firstname"] might be null, and calling ToString() on a null value will throw an exception.

    You can use the null-conditional operator (?.) and the null-coalescing operator (??) to safely access the value and provide a default if it's null.

    Here is the code:

    MyUser.Firstname = MyDataSet.Tables[0].Rows[0]["firstname"]?.ToString() ?? "";