Phiter Fernandes Phiter Fernandes - 1 year ago 62
C# Question

What is this extra interrogation in null coalescence operator

I have this conditional:

if (dr_dados["DAT_SAIDA"] != null)
txtDataSaida.Text = "";
txtDataSaida.Text = dr_dados["DAT_SAIDA"].ToString();

I'm using Jetbrain's ReSharper and it told me I could transform into a ternary operation.

So, it became this:

txtDataSaida.Text = (dr_dados["DAT_SAIDA"] != null) ? dr_dados["DAT_SAIDA"].ToString() : "";

But then it told me I could transform into a null coalescence operation, and it gave me this:

txtDataSaida.Text = dr_dados["DAT_SAIDA"]?.ToString() ?? "";

I sort of know what the null coalescence operation does, but there was something different, something I haven't seen before and I'd like to know what it is.

This extra interrogation right here:

txtDataSaida.Text = dr_dados["DAT_SAIDA"]?.ToString() ?? "";

What does it do/mean?

Answer Source

It is a Null-Conditional Operator.

It is used to check for null before actually performing the member access. If the member you are going to access is in fact null, then no exception will be thrown, but rather a null value will be returned.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download