Data Output and Formatting

You’ve already seen on numerous occasions the use of Console.WriteLine(). This is a multipurpose method for outputting values to the console. The input to this method can be any primitive datatype and any C# object.

WARNING

Objects will not present their values correctly to Console.WriteLine() if they do not provide an override of the public String ToString() method.

When primitive types are combined with Strings in an expression the result will be a String. Consider the example below

error in output - missing the word “be”

Even if the expression began with a numerical value, it would still result in a String. When primitive types are combined with the String type, there is an implicit conversion of the primitive types to a String. For objects, you must supply a method to convert the object into a String. C# provides the conversion method ToString() on all primitives. You can call this directly or the compiler will call it for you when the primitive is included in an expression that involves Strings.

Constructing complex string outputs can be tedious and error prone. We’ve all seen code like this

C# supports composite formatting. A list of objects and a composite format string are used together to create the resultant string. The format string is intermixed with indexed placeholders (format items) that correspond to the items in the list of objects. The resultant string is the format string intermixed with the values from the indexed list of objects.

Console.WriteLine() supports composite format strings. We will use String.Format() for our examples here. Consider the above example rewritten using composite formate strings

Format items have the following syntax - {index[, alignment][:formatString]}

String Interpolation

C# 6 introduces the idea of interpolated strings. This simplified the creation of complex string expressions even more. An interpolated string begins with a dollar character ($). The string comprises of a sequence of characters intermixed with expressions enclosed between left and right curly braces. The expression within the curly braces is evaluated first, the result is then projected into the regular sequence of characters.

Is the $ notation string interpolation fast? Why do I see examples of code using other approaches? The $ notation is new, so lots of examples you see use approaches that people had to use before. There is no performance difference - so do whichever you think is most readable and maintainable.