Skip to content

Instantly share code, notes, and snippets.

@marcin-chwedczuk
Last active December 28, 2018 17:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcin-chwedczuk/3e11b26b603aec920f2eb7b06e40a895 to your computer and use it in GitHub Desktop.
Save marcin-chwedczuk/3e11b26b603aec920f2eb7b06e40a895 to your computer and use it in GitHub Desktop.
C#, null and using statement

Do you know that C# supports using null values with using statements. For example the following program compiles and runs without any problems:

public class Program
{
	public static void Main()
	{
		using(var x = CreateIDisposable()) {
			// prints x = <null>
			Console.WriteLine("x = {0}", x?.ToString() ?? "<null>");	
		}
	}
	
	public static IDisposable CreateIDisposable() => null;
}

This behaviour is mandated by C# language specification. You can check that yourself by reading relevant sections of the spec.

This behaviour can have many interesting usages. For example to add an additional field to every log entry in Serilog you must write:

// borrowed from: https://github.com/serilog/serilog/wiki/Enrichment#the-logcontext
log.Information("No contextual properties");

using (LogContext.PushProperty("A", 1))
{
    log.Information("Carries property A = 1");

    using (LogContext.PushProperty("A", 2))
    using (LogContext.PushProperty("B", 1))
    {
        log.Information("Carries A = 2 and B = 1");
    }

    log.Information("Carries property A = 1, again");
}

Note that LogContext.PushProperty returns an object that must be disposed.

But what if you want to add a field to LogContext only if the field value is present? No problem, just use a method like this:

public static IDisposable AddUserNameToLogContext() {
	var userName = ExtractUserName();
	
	if (userName != null) {
		return LogContext.PushProperty("UserName", userName);	
	}
	
	return null; // null but it is not a problem in C#
}

// And usage...
using(AddUserNameToLogContext()) {
	log.Information("Attempt to open a document...");	
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment