Blog Archives

The C# Null Coalesce Operator

This post was written partly as a reminder to myself that the C# null coalesce operator exists and can be used effectively to write concise readable code. But what is it?

The Null Coalesce operator in C# is a shorthand way of returning a value but specifying a default if that value is null. This is easily demonstrated using a quick example.

String text = "Hello";
String greeting = text ?? "The greeting was null";

In this case, greeting is assigned the value of text unless text is null. In that case it is given a default value of “The greeting was null”. Clearly this could be achieved by other means such as an if..else statement or a ternary operator, however this method provides a very terse syntax. In addition it deals well with results of direct method calls. For example:

String value = MyFunction() ?? "No value returned";

is much better than

String value2 = MyFunction() != null ? MyFunction() : "No value returned";

and more efficient too as the function is only called once.

It should be noted though that it only deals with nulls and understandably does not handle empty strings. For this the String.IsNullOrEmpty can be used instead.

Newlines in a Textbox

I have been implementing some enhancements to an in-house test client application my company uses. It is a Windows Forms application which I wanted to add a textbox to for adding notes to test cases. The Textbox was multi-line and accepts carriage returns. The content of the textbox is then serialized (along with other values) and saved to a file. The file can then be retrieved later, deserialized and used to re-populate the form.

I noticed that whilst the newlines were saved in the file, when re-populating the textbox, the newlines were not displayed and all of the text was on one line. Debugging the app indicated that when reading the file, the newlines were still in place and indicated by \n in the Watch window. After a bit of research, it seems I needed to replace the \n instances with the correct newline characters recognised by C# using the Environment.Newline function. In the end I wrapped this up in a small extension method.

internal static string PreserveFormatting(this string source)
     return source.Replace(((char)10).ToString(), Environment.NewLine);