1

Possible Duplicate:
What do two question marks together mean in C#?

can any one explain this syntax.

protected string CompanyProductSeriesId
{ 
   get 
   { 
       return Request.QueryString["CPGId"] 
              ?? (ViewState["CPSId"] == null 
                  ? "" 
                  : ViewState["CPGId"].ToString()); 
   } 
}

I want to under stand the ?? in this syntax.

Community
  • 1
  • 1
Ashfaq Shaikh
  • 1,648
  • 12
  • 20

5 Answers5

11

?? is the null-coalesce operator.

It returns the first operand from the left that is not null.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
2

A = B ?? C

A = C if B == NULL

A = B if B is not NULL

Below is sraightforward implementation of CompanyProductSeriesId property getter, I believe it is self-explained:

string returnValue;

if (Request.QueryString["CPGId"] != null)
{
   returnValue = Request.QueryString["CPGId"];
}
else
{
   if (ViewState["CPSId"] == null)
   { 
      returnValue = "";
   }
   else
   {  
      returnValue = ViewState["CPGId"].ToString()); 
   }
}

return returnValue;
sll
  • 61,540
  • 22
  • 104
  • 156
1

?? is called null-coalescing operator, From MSDN -

"The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand."

Does that help?

Harish S
  • 23
  • 4
0

In this case, it will return Request.QueryString["CPGId"], or, if that is null, it will return (ViewState["CPSId"] == null ? "" : ViewState["CPGId"].ToString()).

David
  • 15,750
  • 22
  • 90
  • 150
0

?? Operater works only on Nullable Datatype like int?, DateTime? etc.

Example :

int? a = 5;
int b = a ?? 0; // out put will be 5

int? c = null;
int d = c ?? 0; // output will be 0;
Dewasish Mitruka
  • 2,716
  • 1
  • 16
  • 20