What does "??" do in C#?

This question already has an answer here:

  • What do two question marks together mean in C#? 16 answers

  • A ?? B
    

    is a shorthand for

    if (A == null) 
        B
    else 
        A
    

    or more precisely

    A == null ? B : A
    

    so in the most verbose expansion, your code is equivalent to:

    MemoryStream st;
    if(stream == null)
        st = new MemoryStream();
    else
        st = stream;
    

    Basically it means if MemoryStream stream equals null , create MemoryStream st = new MemoryStream();

    so in this case the following:

    MemoryStream st = stream ?? new MemoryStream();
    

    means

    MemoryStream st;
    
    if (stream == null)
       st = new MemoryStream();
    else 
       st = stream;
    

    It's called a null coelesce operator . More info here: http://msdn.microsoft.com/en-us/library/ms173224.aspx


    It's called a null coalesce operator. See here.

    It means that if stream is null, it will create a new MemoryStream object.

    链接地址: http://www.djcxy.com/p/53842.html

    上一篇: 这个MVC项目的第一行是什么意思?

    下一篇: 什么“??” 在C#中做?