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();
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();
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.