Double question marks is a null coalescing operator. The ??
operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.(msdn)
there are 3 examples for c# double question mark example
In following code: The method above states result is assigned var1‘s value, unless var1 is null, in which case it is assigned var2‘s value. (overflowstack)
1 2 3 | result = var1 ?? var2; |
Example 1:
1 2 3 4 5 6 7 8 9 | int b = 16; int? a=null; //notice: a is null int result= a ?? 2; // result 2 Console.WriteLine(result); Console.ReadLine(); |
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 | int a = 6; int b = 3; Console.WriteLine(a + b / 2); // 7 Console.WriteLine((a + b) / 2); // 4 string s = "Beer"; Console.WriteLine(s is string); // True string notNullString = s; string nullString = null; Console.WriteLine(nullString ?? "Unspecified"); // Unspecified Console.WriteLine(notNullString ?? "Specified"); // Beer |
Example 3:
Old Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public static int? doubleMark(int? num1,int? num2) { int num3= 100; if (num1 != null) { return num1; } if (num2 != null) { return num2; } return num3; } static void Main(string[] args) { int? result1 = doubleMark(null, 125); int? result2 = doubleMark(521, null); int? result3 = doubleMark(null, null); Console.WriteLine(result1); // 125 Console.WriteLine(result2); // 521 Console.WriteLine(result3); // 100 Console.ReadLine(); } |
New Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public static int? doubleMark(int? num1,int? num2) { int num3= 100; return (num1 ?? num2) ?? num3; } static void Main(string[] args) { int? result1 = doubleMark(null, 125); int? result2 = doubleMark(521, null); int? result3 = doubleMark(null, null); Console.WriteLine(result1); // 125 Console.WriteLine(result2); // 521 Console.WriteLine(result3); // 100 Console.ReadLine(); } |
Example 4:
1 2 3 4 5 6 7 8 | string name1 =null ; string name2= "Marc"; Console.WriteLine(name1 ?? name2); //output Marc Console.WriteLine(name2 ?? name1); //output Marc Console.ReadLine(); |