Learn all new features in C# 10 (Part 2)
Table of Contents
This is the part 2 of the series in which I shall be discussing the following:
- Interpolated String Handlers
- Global Using Directive
- File Scoped Namespace Declaration
YouTube version
https://youtu.be/iztV4_69xzE
What is an Interpolated String ?
String interpolation provides a more readable, convenient syntax to format strings. The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions like {name} in the code snippet for string interpolation below. The pair of braces { } contains a variable whose value is resolved directly at runtime.
string name = "Mark";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.
In the above code the first WriteLine statement uses composite formatting and the second one uses string interpolation. An inspection shows that it is easier to read the second console statement which uses an interpolated string.
Beginning with C# 10, when an interpolated string is used, the compiler checks if the interpolated string is assigned to a type that satisfies the interpolated string handler pattern. An interpolated string handler is a custom type that converts the interpolated string into a string or processes the placeholder expression in an interpolated string.
Without a custom handler, placeholders are processed similar to String.Format. Each placeholder is formatted as text, and then the components are concatenated to form the resulting string.
An Use Case Scenario
- You may require none of the resulting strings are greater than some limit, such as 80 characters. You can process the interpolated strings to fill a fixed-length buffer, and stop processing once that buffer length is reached.
- You may have a tabular format, and each placeholder must have a fixed length. A custom handler can enforce that, rather than forcing all client code to conform to that rule.
An initial implementation on Visual Studio
This tutorial is based on this article. So let’s now switch back to Visual studio and start working on the same project that we started in part 1. Let’s create a Logger class in our project by right clicking the project and then following Fig. 1

On the Add New Item dialog give the Name Logger and click Add (Fig. 2)

Now copy and paste the code below to override the default code created within the namespace WhatsNewInCSharp
public enum LogLevel
{
Off,
Critical,
Error,
Warning,
Information,
Trace
}
public class Logger
{
public LogLevel EnabledLevel { get; init; } = LogLevel.Error;
public void LogMessage(LogLevel level, string msg)
{
if (EnabledLevel < level) return;
Console.WriteLine(msg);
}
}
This Logger supports six different levels. When a message won’t pass the log level filter, there’s no output. The public API for the logger accepts a (fully formatted) string as the message. All the work to create the string has already been done.
Implement the handler pattern
An interpolated string handler which we shall build (that recreates the current behavior) is a type that must have the following characteristics:
- System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute is applied to the type
- It should have a constructor that has two int parameters, literalLength and formatCount
- A public
AppendLiteralmethod with the signature:public void AppendLiteral(string s) - A generic public
AppendFormattedmethod with the signature:public void AppendFormatted<T>(T t).
Internally, the builder creates the formatted string, and provides a member for a client to retrieve that string. The following code shows a LogInterpolatedStringHandler type that meets these requirements:
Next we shall paste the following code in our Logger class below the existing code (for the LogMessage method)
[InterpolatedStringHandler]
public ref struct LogInterpolatedStringHandler
{
// Storage for the built-up string
StringBuilder builder;
// Add the receiver argument:
public LogInterpolatedStringHandler(int literalLength, int formattedCount)
{
builder = new StringBuilder(literalLength);
Console.WriteLine($"\tliteral length: {literalLength}, formattedCount: {formattedCount}");
}
public void AppendLiteral(string s)
{
Console.WriteLine($"\tAppendLiteral called: {{{s}}}");
builder.Append(s);
Console.WriteLine($"\tAppended the literal string");
}
public void AppendFormatted<T>(T t)
{
Console.WriteLine($"\tAppendFormatted called: {{{t}}} is of type {typeof(T)}");
builder.Append(t?.ToString());
Console.WriteLine($"\tAppended the formatted object");
}
internal string GetFormattedText() => builder.ToString();
}
Next we add an overload to LogMessage in the Logger class. Accordingly copy and paste the following code for this overloaded method below the original LogMessage method
public void LogMessage(LogLevel level, LogInterpolatedStringHandler builder)
{
if (EnabledLevel < level) return;
Console.WriteLine(builder.GetFormattedText());
}
You don’t need to remove the original LogMessage method as the compiler will prefer a method with an interpolated handler parameter which has a stringbuilder over a method with a string parameter when the argument is an interpolated string expression.
To test the new handler is invoked, use the following code (within a Main( ) method)
var logger = new Logger() { EnabledLevel = LogLevel.Warning };
var time = DateTime.Now;
logger.LogMessage(LogLevel.Error, $"Error Level. CurrentTime: {time}. This is an error. It will be printed.");
logger.LogMessage(LogLevel.Trace, $"Trace Level. CurrentTime: {time}. This won't be printed.");
logger.LogMessage(LogLevel.Warning, "Warning Level. This warning is a string, not an interpolated string expression.");
If you click F5 or the green icon on top to run the application, it shows the following command window

Tracing through the output, you can see how the compiler adds code to call the handler and build the string:
- The compiler adds a call to construct the handler, passing the total length of the literal text in the format string, and the number of placeholders.
- The compiler adds calls to
AppendLiteralandAppendFormattedfor each section of the literal string and for each placeholder. - The compiler invokes the
LogMessagemethod using theCoreInterpolatedStringHandleras the argument.
Finally, notice that the last warning doesn’t invoke the interpolated string handler. The argument is a string, so that call invokes the other overload with a string parameter.
The next heading on debugging the application (albeit a bit painstakingly 🙁 ) confirms our comments in this paragraph about tracing through the output
Debug through the application
To debug the application, let’s place a breakpoint anywhere in the Main() method and click F11 which brings the console window after building the application. On placing the code and command console output windows adjacent to each other as

Stepping through F11 it hits the above breakpoint

Click F11 again to show this

Click F11 again brings the following:

F11 again takes the control to next code line

Clcking F11 again takes the focus to next code line calling LogMessage method. Stepping through F11 takes control to the constructor that takes two int arguments as below:

Stepping through F11 two times next gives the following display:

Taking F11 again gives the following display:

Next F11 takes to AppendLiteral method

Stepping through F11 thrice steps through the complete method and shows the display as:

Another stepping through F11 shifts the control to AppendFormatted method with the screen following next three step throughs showing

Again step through F11 takes it to AppendLiteral method again and following two F11 clicks shows the displays as

The control then shows the following log after a few more step through


Stepping through F11 three more times, displays on the console the following

Next F11 step through takes the control to next call to the LogMessage from where it started earlier

The control repeats the steps all over again calling the AppendLiteral again and writing the following display on the console

Next, like the last cycle it calls the AppendFormatted method and updates the display further

Next few F11 step throughs takes the control through the AppendLiteral method again and adds to the display :

Next F11 call shifts the control to LogMessage overload and returns the control since Enabled Level (Warning ) < input level (Trace)
Finally the last time LogMessage is called with a string (not an interpolated string), so it enters the original LogMessage method passing the string and writing the message to the console as follows:

Pressing the F11 twice more exits the Main() method and ends the program. That would seem a bit too much in a blog post about running through the debugging process for an interpolated string handler! However, viewing it in the context of it’s uniqueness and confomance to certain characteristics stated at the start, I think it will still be worth the effort!
Global Using Directives
The using directive allows us to use types defined(used) in a namespace without writing the fully qualified namespace of that type. This is in usage since C# 1.0 and put at the top left of every single cs file in a project. As a simple example:
Console.WriteLine("Hello World"); //Assumes a using System namespace at the top
without this Using System namespace, the code would be:
System.Console.WriteLine("Hello World");
That’s no big deal writing System.Console.WriteLine, but you would not expect anyone to have to write
System.Collections.Generic.List<System.Threading.Tasks.Task<System.IO.Stream>>
You’d expect to see just List<Task<Stream>>. So we can see that these Using statements declutter code. OK, then what is the big deal in keeping Using statements in every file as we have used to do in the past?
The downside is that C# files often start with a load of using directives. If we add a class to our project, then these using statements are present by default, irrespective of if they would be required ever in that file (or in a class contained in that .cs file). Some people consider this to be mere noise, meaningless ‘ceremony’ to be trudged through before you can get to the real content.
C# 10 introduces the new global using directive language feature so that we don’t have to write the same using directives again and again in hundreds of files. We turn an ordinary using directive into a global one by adding the global modifier. E.g.:
global using System;
This global modifier can be added in any source file within the project. The effect of using global this way would be the same as writing using System ; directive at the top of every file in our project.
How to Use Global Using in Visual Studio ?
Let’s go launch our Visual Studio 2022 project again and create a new file named GlobalUsing.cs at the project level and paste the code below (to overwrite the default code)
global using System.Runtime.CompilerServices; global using System.Text;
These two usings were required for our Logger class in the previous article on implementing string handler interpolation . Next remove the above namespace in the Logger.cs file. We can easily check that there are no syntax errors present and we are able to run the application as before.
File Scoped Namespace Declaration
The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.
namespace SampleNamespace
{
class SampleClass { }
interface ISampleInterface { }
struct SampleStruct { }
enum SampleEnum { a, b }
delegate void SampleDelegate(int i);
namespace Nested
{
class SampleClass2 { }
}
}
In C# 10, Microsoft has allowed the namespace to be written terminated by ; without the braces { }. So the above code snippet could be written as below. Note in this file-scoped namespace, no nested namespaces are allowed. The advantage of writing a file-scoped namespace is that it saves horizontal and vertical spa ces and indenting.
namespace SampleNamespace;
class SampleClass { }
interface ISampleInterface { }
struct SampleStruct { }
enum SampleEnum { a, b }
delegate void SampleDelegate(int i);
To test the file-scoped namespace changes in C#, let’s go back to our Visual Studio 2022 working project WhatsNewInCSharp and change any of the .cs files . The following code shows the changes made to WithExpressionEx.cs :
namespace WhatsNewInCSharp;
internal class WithExpressionEx
{
public struct NamedPoint
{
public NamedPoint()
{
Name = string.Empty;
ValueX = 0;
ValueY = 0;
}
public NamedPoint(string name, int x, int y)
{
Name = name;
ValueX = x;
ValueY = y;
}
public string Name { get; init; }
public int ValueX { get; init; }
public int ValueY { get; init; }
}
public static void Main()
{
var p1 = new NamedPoint("A", 0, 0);
Console.WriteLine($"{nameof(p1)}: {p1.Name},{p1.ValueX},{p1.ValueY}"); // output: p1: NamedPoint { Name = A, X = 0, Y = 0 }
var p2 = p1 with { Name = "B", ValueX = 5 };
Console.WriteLine($"{nameof(p2)}: {p2.Name},{p2.ValueX},{p2.ValueY}"); // output: p2: NamedPoint { Name = B, X = 5, Y = 0 }
var p3 = p1 with
{
Name = "C",
ValueY = 4
};
Console.WriteLine($"{nameof(p3)}: {p3.Name},{p3.ValueX},{p3.ValueY}"); // output: p3: NamedPoint { Name = C, X = 0, Y = 4 }
var NamedPoint1 = new
{
Name = "Rory",
X = 100,
Y = 200
};
var NamedPoint2 = NamedPoint1 with { Name = "Johnny", X = 300 };
Console.WriteLine(NamedPoint1);
Console.WriteLine(NamedPoint2);
}
}
If we build and run the application it works perfectly as before.
If now we change the <LangVersion> to C#9 as below in the project file (Fig. 22)

We see all the errors coming up due to the version downgrading to C# 9 as the following screenshots show:




The mouseover on the errors recommend using the version 10.0 that incorporates all these new features which were not part of the earlier versions.
Follow Me Here