[c#] C# equivalent of the IsNull() function in SQL Server

In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.

For example, I want to do something like:

myNewValue = IsNull(myValue, new MyValue());

instead of:

if (myValue == null)
  myValue = new MyValue();
myNewValue = myValue;

Thanks.

This question is related to c# .net sql-server isnull

The answer is


Use below methods.

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static long? IsNull(long? expression, long? replacement)
    {
        if (expression.HasValue)
            return expression;
        else
            return replacement;
    }

    /// <summary>
    /// Returns replacement value if expression is null
    /// </summary>
    /// <param name="expression"></param>
    /// <param name="replacement"></param>
    /// <returns></returns>
    public static string IsNull(string expression, string replacement)
    {
        if (string.IsNullOrWhiteSpace(expression))
            return replacement;
        else
            return expression;
    }

I've been using the following extension method on my DataRow types:

    public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
    {
        string val = defaultValue;
        if (row.Table.Columns.Contains(colName))
        {
            if (row[colName] != DBNull.Value)
            {
                val = row[colName]?.ToString();
            }
        }
        return val;
    }

usage:

MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");

I'm checking for the existence of the column first because if none of query results has a non-null value for that column, the DataTable object won't even provide that column.


public static T isNull<T>(this T v1, T defaultValue)
{
    return v1 == null ? defaultValue : v1;
}

myValue.isNull(new MyValue())

This is meant half as a joke, since the question is kinda silly.

public static bool IsNull (this System.Object o)
{
   return (o == null);
}

This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.

Then you can save tons of code by doing:

if (foo.IsNull())

instead of the super lame:

if (foo == null)

Use the Equals method:

object value2 = null;
Console.WriteLine(object.Equals(value2,null));

Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:

newValue = (oldValue is DBNull) ? null : oldValue;

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

For working with DB Nulls, I created a bunch for my VB applications. I call them Cxxx2 as they are similar to VB's built-in Cxxx functions.

You can see them in my CLR Extensions project

http://www.codeplex.com/ClrExtensions/SourceControl/FileView.aspx?itemId=363867&changeSetId=17967


You Write Two Function

    //When Expression is Number
    public static double? isNull(double? Expression, double? Value)
    {
        if (Expression ==null)
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }


    //When Expression is string (Can not send Null value in string Expression
    public static string isEmpty(string Expression, string Value)
    {
        if (Expression == "")
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }

They Work Very Well


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to isnull

how to check for null with a ng-if values in a view with angularjs? jQuery check if Cookie exists, if not create it Equivalent of SQL ISNULL in LINQ? C# equivalent of the IsNull() function in SQL Server