3

I found this new and interesting code in my project. What does it do, and how does it work?

MemoryStream stream = null;
MemoryStream st = stream ?? new MemoryStream();
Michael Petrotta
  • 58,479
  • 27
  • 141
  • 176

3 Answers3

8
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;
Sina Iravanian
  • 15,521
  • 4
  • 30
  • 44
1

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

mnsr
  • 12,097
  • 3
  • 51
  • 78
0

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

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

whastupduck
  • 1,148
  • 10
  • 25