Posted by: Rhonda Tipton | September 27, 2008

The C# Null Coalescing Operator (??)

I was looking through some code the other day and ran across something that looked remotely familiar.  It was the null coalescing (??) operator.  I had read about this operator, but never used it.  It was introduced with the .NET 2.0 Framework.

The null coalescing operator basically checks to see if a value is null and if so returns an alternate value.  Below is a simple example.

View the C# code sample [HERE] 

Results

Related Content

“I am learning all the time.  The tombstone will be my diploma.” -Eartha Kitt


Responses

  1. [...] The C# Null Coalescing Operator (??) (Rhonda Tipton) [...]

  2. Heard of it to
    C++ has a similar thing just it has to option for true and false
    greetings

  3. @Patryksharks321: You’re talking about the conditional operator (?:) which C# also has.

    I abuse this operator in “singleton-like” properties…

    e.g.
    private object myObject = null;
    public object MyObject
    {
    get { return myObject ?? ( myObject = new object ( ) ); }
    }


Leave a response

You must be logged in to post a comment.

Categories