CSharp ?? Operator

One of the problems with learning a language early in its life cycle is that by the time version three comes out, you never look at or implement any of the new features.

There are two reasons for this.  First, the features you are using already cover 80% of the features you need.  Second, you never look at the manual to discover what new features are available–features that may help you write your code more efficiently.

The CSharp ?? operator is one such feature.

We’ve all written code that looks something like this:

if (s == null)
    s = "some default value";

Since version one, we could write this with less text by saying

s = s == null ? "some default value" : s;

But did you know you could write that same code in even less code using the double question mark operator?

s = s ?? "some default value";

There are some who might say that each shortened form makes the code less readable.  For those people I say, once you know the syntax it is no more unreadable than any other code we might write.

Related Post

2 Responses to “CSharp ?? Operator”

  • I think it will be better if you declare your variable using function, there it might much easier to call the variable when the condition needs it.

    • Dave:

      I’m sorry, I’m not following your logic.

      You are going to call a function to do what this does in one line so it is easier to call?

      What makes it easier to call?

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear