123

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.

Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
HAdes
  • 16,713
  • 22
  • 58
  • 74

10 Answers10

228

It's called the null coalescing (??) operator:

myNewValue = myValue ?? new MyValue();
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 4
    I tried to use the null-coalescing operator but kept getting the error *Operator '??' cannot be applied to operands of type 'bool?' and 'int'*. The error was misleading. The problem was that I was trying to assign a an int in the right-hand operand position to a boolean variable. I had to change from `this.BinaryExists = vModel.BinaryExists ?? 0;` to `this.BinaryExists = vModel.BinaryExists ?? false;`. – Kuyenda Jul 07 '11 at 14:00
14

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;
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • 16
    Nitpick: I know lots of places refer to this as the ternary operator. There happens to only be one ternary operator at the moment, but that's a property of it, not its name. It's really the conditional operator. If C# ever gains another ternary operator, there'll be a lot of confusing books. – Jon Skeet Oct 04 '08 at 06:42
  • you can cast dbnull to an object ((object)oldValue ?? (object)DBNull.Value)) – Jeremy Gray Mar 02 '11 at 19:17
  • 1
    @JeremyGray `(object)oldValue ?? (object)DBNull.Value)` would be equivelent to `((object)oldValue == null) ? (object)DBNull.Value : (object)oldValue` which is different the the problem Robert Rossney's solution addresses. – Trisped Jan 26 '13 at 00:35
5
public static T isNull<T>(this T v1, T defaultValue)
{
    return v1 == null ? defaultValue : v1;
}

myValue.isNull(new MyValue())
Rudy
  • 51
  • 1
  • 1
5

Use the Equals method:

object value2 = null;
Console.WriteLine(object.Equals(value2,null));
serializer
  • 1,003
  • 2
  • 13
  • 27
1

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

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • Looks like they changed all the URLs on CodePlex. Try this: http://clrextensions.codeplex.com/SourceControl/changeset/view/63575#667137 – Jonathan Allen May 07 '12 at 19:00
0

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

  • 2
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Luca Kiebel May 25 '18 at 20:00
0

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.

Denis M. Kitchen
  • 1,142
  • 2
  • 14
  • 24
0

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;
    }
sushil suthar
  • 639
  • 9
  • 12
0
    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
-10

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)
FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • This does not answer the question. – Eric Schoonover Oct 04 '08 at 05:23
  • 12
    You don't know what ISNULL in sql server does, FlySwat. – ClayKaboom Jul 19 '11 at 18:35
  • 1
    Maybe this works differently in C#, but I know in VB this would NOT work for testing the object is null as the OP is asking about. I tried this myself. I made just such an extension to System.Object. Problem is the extension method requires an actual `Object` object upon which to operate, and if the object was Nothing (precisely the case you're trying to test for in this Q) there was no instance for the extension class to operate on and thus it would throw a NullObject exception. – eidylon Aug 31 '12 at 17:48
  • @eidylon Looks like you cannot access an extension method on a `Object` in VB. See [this SO question](http://stackoverflow.com/questions/2402660/why-does-this-extension-method-throw-a-nullreferenceexception-in-vb-net) or [this blog post](http://blogs.msdn.com/b/vbteam/archive/2007/01/24/extension-methods-and-late-binding-extension-methods-part-4.aspx). – Trisped Jan 26 '13 at 00:57