Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "??" do in C#? [duplicate]

Tags:

c#

.net

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();
like image 203
sivaprakash Avatar asked Feb 03 '26 01:02

sivaprakash


1 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;
like image 127
Sina Iravanian Avatar answered Feb 05 '26 14:02

Sina Iravanian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!