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
  • 59,888
  • 27
  • 145
  • 179

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
  • 16,011
  • 4
  • 34
  • 45
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,337
  • 4
  • 53
  • 79
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,156
  • 11
  • 25