What does ?? do

Topics: CAB & Smart Client Software Factory
Jul 3, 2006 at 6:25 PM
originally posted by: kgreed

I am new to c# and CAB
Would anyone mind explaining what ?? does in the following code sample?

public void Show(IWorkspace parentWorkspace)
customerSummaryView = customerSummaryView ?? Items.AddNew<CustomerSummaryView>();
Jul 3, 2006 at 9:22 PM
originally posted by: aras03k

Basically it's just a quick way of ensuring that customerSummaryView should use the existing reference if it is not null and if it is then instead use the right operand of ?? which constructs the View by adding it to the workitem.
Jul 4, 2006 at 9:32 AM
originally posted by: austinlamb

To expand on what aras03k said...

The ?? operator is a shorthand notation in C#, introduced in C# 2.0 - it's just syntatic sugar, not any new functionality. To illustrate, see this example:

This line:

customerSummaryView = customerSummaryView ?? Items.AddNew<CustomerSummaryView>();

Is equivalent to this block of code:

if(customerSummaryView == null) {
customerSummaryView = Items.AddNew<CustomerSummaryView>();
else {
customerSummaryView = customerSummaryView;

Or, for another example that doesn't have a pointless else clause, the ?? operator can do things like this:

This line:

someVariable = myNullableThing ?? myGuaranteedNotNullThing;

Which is equivalent to:

if (myNullableThing == null) {
someVariable = myGuaranteedNotNullThing;
else {
someVariable = myNullableThing;

So in the CAB sample you show, it's just a way of saying "create a new view, unless the existing one is not null, in which case do nothing." It just does it all in one line, which may or may not be preferable to you, but is functionally the same as an if/else block.
Jul 4, 2006 at 2:43 PM
originally posted by: kgreed

That makes sense
Thank you