AndyD273
AndyD273

Reputation: 7279

Universal DBNull check

I have a VB.Net function that is useful for checking if a database record is null or not, and replace it with a default value if it is.

Public Function NZ(input As Object, Optional ifNull As Object = "") As Object
    If IsDBNull(input) Or input Is Nothing Then
        Return ifNull
    Else
        Return input
    End If
End Function

I'm trying to get the same functionality in C#, but it doesn't like using objects the same way.

The closest I've gotten is

    public static object NZ(object input, object ifNull)
    {
        if(input == DBNull.Value || input == null)
        {
            return ifNull;
        }
        else
        {
            return input;
        }
    }

but I get several errors with "cannot convert object to string" and the like. I have tried to make a more specific version

    public static string NZ(string input, string ifNull)
    {
        if (input == DBNull.Value || input == null)
        {
            return ifNull;
        }
        else
        {
            return input;
        }
    }

but that gives a "Operator '==' cannot be applied to operands of type string and DBNull"

I'm hoping there is an easy way to do this.

Upvotes: 0

Views: 92

Answers (2)

Mayur Ekbote
Mayur Ekbote

Reputation: 2080

Use Convert.IsDbNull

The code will be something like this:

 public static string NZ(object input, string ifNull)
    {
        return Convert.IsDbNull(input) ? ifNull : input;
    }

If you want it to be more concise, write an extension method:

public static class DbNullExt
{
      public static string ValueOrDefault(this object input, string ifNull)
      => Convert.IsDbNull(input) ? ifNull : input?.ToString();

      public static string ValueOrDefaultIfDbNullOrNull(this object input, string ifNull)
      => Convert.IsDbNull(input) ? ifNull : input?.ToString() ?? ifNull;
}

And then simply invoke it as

var valueOrDefault = input.ValueOrDefault("ifItIsDbNull");

Upvotes: 3

huMpty duMpty
huMpty duMpty

Reputation: 14460

Use Information.IsDBNull

public object NZ(object input, object ifNull)
{
    if (Information.IsDBNull(input) || input == null)
        return ifNull;
    else
        return input;
}

Upvotes: 1

Related Questions