开发者

usage of double question mark in .net [duplicate]

This question already has answers here: Closed 11 years ago. 开发者_C百科

Possible Duplicate:

What do two question marks together mean in C#?

What is the usage of ?? in .Net? How it can be used to check while assigning the variables? Could you please write some code snippet to better explain the content ? Is it related with some nullable ?


The operator '??' is called null-coalescing operator, which is used to define a default value for a nullable value types as well as reference types.

It is useful when we need to assign a nullable variable a non-nullable variable. If we do not use it while assigning, we get an error something like

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

To overcome the error, we can do as follows...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenConsole
{
    class Program
    {    
        static void Main(string[] args)
        {
            CoalescingOp();
            Console.ReadKey();
        }

        static void CoalescingOp()
        {
            // A nullable int
            int? x = null;
            // Assign x to y.
            // y = x, unless x is null, in which case y = -33(an integer selected by our own choice)
            int y = x ?? -33;
            Console.WriteLine("When x = null, then y = " + y.ToString());

            x = 10;
            y = x ?? -33;
            Console.WriteLine("When x = 10, then y = " + y.ToString());    
        }
    }
}


It's the null coalescing operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜