Real World C# 6 Impact

BY Matthew Lovelady

We are constantly upgrading our programming tools and languages to take advantage of the latest technologies. The connected, interactive touchscreen applications that we are building today are vastly different than the standalone programs we developed 12 years ago. C# is one of the programming languages that we are currently using to create much richer (and much more reliable) visitor experiences for museums, libraries and corporate visitor spaces.

Now C# 6.0 is upon us with all of its goodies in tow. Let’s look at an actual real world transformation from C# 5 to C# 6. The latter allows us to remove a good portion of the ceremony around our intent. In other words, we can remove several lines of what we might call “boilerplate” code.

For example, let’s assume we need a simple ticker for counting the number of times library patrons use a touchscreen kiosk, or the number of questions presented in an interactive museum game. This ticker is created in a little snippet of code that we call a “class.” This class has one simple task: manage the number of ticks and expose a few simple methods. (Methods are for checking and mutating the state of the ticker. Examples might include Tick ,IsExhausted, Reset, or an override of ToString.) So let’s see what that implementation looks like in C# 5.

public class Countdown
{
private readonly int mMaxTicks;
private int mTicks;

public event System.Action Exhausted;

public Countdown(int maxTicks)
{
mMaxTicks = maxTicks;
}

public void Tick()
{
++mTicks;
if (IsExhausted)
{
var lexhausted = Exhausted; // doing this for thread safety
if (lexhausted != null)
lexhausted.Invoke();
}

}

public int Ticks
{
get
{
return mTicks;
}
}

public int MaxTicks
{
get
{
return mMaxTicks;
}
}

public bool IsExhausted
{
get
{
return Ticks > MaxTicks;
}
}

public void Reset()
{
mTicks = 0;
}

public override string ToString()
{
return string.Format("{0} / {1} ticks", Ticks, MaxTicks);
}
}

That example represents pretty standard and reasonable code for C# 5. However with C# 6, we can make a few improvements. We can trim our code to focus on the core computing work.

public class Countdown
{
private readonly int mMaxTicks;
private int mTicks;

public event System.Action Exhausted;

public Countdown(int maxTicks)
{
mMaxTicks = maxTicks;
}

public void Tick()
{
++mTicks;
if (IsExhausted)
Exhausted?.Invoke();// checks for null and does the same thing we were doing above for thread safety, just behind the scenes
}

public int Ticks => mTicks;

public int MaxTicks => mMaxTicks;

public bool IsExhausted => Ticks > MaxTicks;

public void Reset() => mTicks = 0;

public override string ToString() => $"{Ticks} / {MaxTicks} ticks";
}

The above code samples are functionally equivalent. The latter simply has a lower noise to signal ratio. Much of the boilerplate code is stripped away, and we are left with only what we are actually computing. The null conditional (or as it is affectionately called the “elvis operator” because it looks like Elvis with the eyes and the hair swoop) is especially useful. In most cases we will not have to do a null check. However, we may need to do null checking in cases where program branches are based off of a reference being null.

Beyond this ticker example, there are certainly other features and improvements in C# 6 that were not demonstrated here. There is one feature in particular I want to demonstrate in a way I have not seen before. The “nameof” feature is new to C# 6, and it has potential to be useful in several ways. The most common use I anticipate is for exception handling and logging. Since many of our touchscreen interactives and custom applications access data over the Internet or local network, we frequently need a way to log errors or exceptions that occur for remote diagnostics and support.

Another common task is create a UI element for users to receive information or interact with the content. For example, we might need an element to display Flickr photos for a college campus directory. In such a scenario, we would also want to display the photo caption which could have text characters, emojis and HTML formatting. In C# 5, we can create this UI element dynamically by building a XAML element from a string. This approach is not a common solution, but I have had to use in the past to preserve the non-text characters returned in the data. (XAML is the UI framework we are using–it’s a C# thing.)

(T)XamlReader.Load($"<{typeName}> {...}");

In the code above, we passed in the typeName as a string, not exactly type safe or future proof. This is C#, so we have a type system. Let’s use it. And with C# 6, now we can.

(T)XamlReader.Load($"<{nameof(T)}> {...}");

Much better, no magic strings for us to fall victim to. By using this code, we can account for using a different type in the future. Therefore, if we want to change the way we display Flickr images in the future, we are covered without any changes to this code. As an added benefit, we also avoid those nasty spellcheck bugs by forcing the computer to retrieve the type name.

That’s it for today. Two quick examples that highlight how C# 6 is easier to write and easier to read. In my opinion that’s a solid win for our programming team and our clients. If you haven’t looked at C# 6 yet, I encourage you to opt in to C# 6 syntax wherever you can in the future.

Scroll Up
 Previous  All works Next