Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coalesce operator in C#?

I think i remember seeing something similar to the ?: ternary operator in C# that only had two parts to it and would return the variable value if it wasn't null and a default value if it was. Something like this:

tb_MyTextBox.Text = o.Member ??SOME OPERATOR HERE?? "default";

Basically the equivalent of this:

tb_MyTextBox.Text = o.Member != null ? o.Member : "default";

Does such a thing exist or did I just imagine seeing this somewhere?

like image 211
Abe Miessler Avatar asked Oct 13 '10 16:10

Abe Miessler


People also ask

What is coalesce in C?

The COALESCE expression allows for user-specified NULL-handling. It is often used to fill in missing values in dirty data. It has a function-like syntax, but can take unlimited arguments, for example: COALESCE(a, b, c, x, y, z) .

What is use of null coalesce operator?

Uses of Null Coalescing Operator: It is used to replace the ternary operator in conjunction with the PHP isset() function. It can be used to write shorter expressions. It reduces the complexity of the program. It does not throw any error even if the first operand does not exist.

What is the benefit of coalescing?

Coalesce is simpler than a CASE statement. It is very much like ISNULL which typically I see used more in code. However, coalesce does have some advantages, including: no truncation, it takes more than 2 parameters, and it is ANSI compliant!

Which of the following is null coalescing operator?

The ?? operator is also known as the null-coalescing operator. It returns the left side operand if the operand is not null else it returns the right side operand.


1 Answers

Yup:

tb_myTextBox.Text = o.Member ?? "default";

http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx

like image 160
Pete Avatar answered Oct 11 '22 23:10

Pete