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.

 


Other post in Advanced CSharp

Other Related Items:

Chopin: MazurkasChopin: MazurkasPillow - Roll (Scribbles)
LINQ in ActionLINQ in Action

LLINQ, Language INtegrated Query, is a new extension to the Visual Basic and C# programming languages designed to simplify data queries and databas... Read More >

If you're new here, you may want to subscribe to the mailing list to get notifications of new post and a virtual tour of past topics. Thanks for visiting!

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?

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor