Reputation: 7279
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
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
Reputation: 14460
public object NZ(object input, object ifNull)
{
if (Information.IsDBNull(input) || input == null)
return ifNull;
else
return input;
}
Upvotes: 1