Photo by Rod Long on Unsplash — Developer Sugar

The joy of Syntactic Sugar — Multiple Output Parameters

James Woodall
5 min readSep 2, 2020

--

Over the past few years under the “new Microsoft”, there have been many efforts to open-source the languages and frameworks that Microsoft develop. .NET Core (Microsoft’s development platform) is fully open-source and developers are actively encouraged to develop applications on non-Windows platforms such as Linux and macOS, something that wouldn’t have happened at all during the previous administration.

Anyway, I write this article while developing in Visual Studio Code on macOS and I came across a new C# feature that serves no other purpose than to put a smile on developers faces all around the globe: Value Tuples.

Why should I care?

How many times have you needed to return 2 or more values from a method? Take this example:

I need a method that generates a partition key and row key for a database from a given input value.

There are a few ways of doing this before tuple values came along. And, none of them are particularly pretty.

Out Parameters

A favourite of C/C++ developers, out parameters give you the ability to return values through method parameters (as opposed to using parameters for inputs).

public string GenerateKeys(string input, out string rowKey) {
// DO SOME WORK
rowKey = “Some new value”;
return “Some other value”;
}
// Calling the method
var partitionKey = GenerateKeys("some input", out string rowKey);

In this example, I’m returning the partition key in the standard fashion but also return the rowKey using an out parameter. This is really ugly though and creates some inconsistencies. It also requires me to declare my partition and row key variables separately which isn’t pretty either. And, if the out parameter is optional, I need to implement and define it anyway or the compiler will get upset (and default out parameters aren’t supported).

Also, if you’re using async Task methods, out parameters don’t work!

Next!

Object Arrays

This option shouldn’t even be discussed, but, a developer I worked with several years ago did this and wasn’t ashamed…

--

--

James Woodall

James has been working in software development for several years and loves programming for web and wearable devices.