Main navigation

An universal app (in regards to the Microsoft platform as Apple uses this same term for something similar but different enough) is made up, at a very high level, of three areas. The first area, the User Interface (UI) is what you see, and for a Universal App it is built either with XAML or HTML. The second is the logic which powers the UI, the logic can go by many names (code behind, controller, view model and more), and we will refer to the logic in this document, as the brains. The UI and brains work together, the brains giving the raw data to the UI which handles laying the data out and styling the data, and the UI providing input to the brains in the form of interactions from the user. The third piece is supporting code which the brains and UI use, for example code which talks to an API or a database. This third piece is sometimes very separate and sometimes very mixed into the brain.

Traditionally if you wanted to build an app which targets multiple platforms, you had to create a custom UI for each platform and traditional software development tied the brain and the UI tightly together which meant that you had to often rewrite the brain or copy & paste between different platforms. This leads to duplication in everything: cost, time to add features, bugs etc…

Microsoft has introduce a concept called Universal Apps, which is a way of creating a single core app which can be run on Windows phone 8.1, Windows 8, 8.1 or 10 and Xbox One (coming soon). The way this works is that the app is partitioned into multiple pieces, one for each target platform and an additional piece called Shared. For this article we will focus on building an app which targets Windows phone 8.1 and Windows 8.1 and thus we will have three pieces in our project.

Microsoft does have other technologies which can support even greater reuse of code, such as Portable Class Libraries (PCL), and there are industry patterns, for example Dependency Injection (DI) which can help but none are essential and none are directly relevant to this document. The take away though is that getting the most reuse of code, will take planning and understanding of software development by skilled and experience developers.

The core idea in a Universal app is what you place as much of the code in the shared partition, allowing each platform to use the exact same UI, brains and supporting code. Modern technologies included in XAML and CSS 3 for HTML allow the UI to respond to different screen sizes and different devices in an intelligent way, thus ensuring one UI can be built and used across all platforms. For the brains, proven practices, such as MVVM, allow the brain to be decoupled from the UI and that allows maximum reuse of that code.

In an ideal scenario you would get 100% of the code in shared however in reality it is between 75% and 95% (based off my own experiences and what the app does & what platforms it targets). The issue is that even for all the best technology today, some UI elements just do not work across different platforms, some features only exist on a specific platform and some optimizations can be made to improve performance or the user experience. In these cases the relevant piece of code or UI is moved out of shared partition and to the actual platform with minor duplication at worst.

A great example of this is settings: On Windows phone the design style says you have one settings page which is accessed from a button in the appbar. Windows 8.1, the design style suggests you do not have the settings in the appbar, but rather you use the settings charm and you make use of flyouts. In traditional development that would require totally separate code for the setting and totally separate UI. Following correct practice, you should be able to have the logic once, in shared, the UI broken into components, also in shared. Then on each platform all that is unique is how you compose those components together.

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

Expression bodied members, which is a new feature in C# 6 and is a very interesting feature which aims to have less lines of code in your app for simple things. What do I mean by simple things? Anything which is ONE statement.

I use the word statement and not line since you can break a statement across multiple lines and it will work. Think of statement to mean, when you hit your first ; you are done.

Here are some examples of one statement code blocks:

// a method with one statement in it
private double Tax()
{
return 1.14;
}
// a read-only property with one statement
public double Price
{
get
{
return CostPrice * Tax();
}
}
// a method calling an event, in this case using the nullet operator
private void RaisePain(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

All examples have one one statement and all examples are also multiple lines of code. The first and last examples are 4 lines of code (4 to 1 ratio) and the second example is 7 lines of code (7 to 1 ratio). Expression Bodied Members aims to get that to a 1 to 1 ratio!

Expression Bodied Members

The name of this feature hints at everything you need to know for this: This is for members (properties, methods etc…), this is an expression and so we will use the => operator and that operator will be followed by the body of the expression. If we apply that logic to the first example we can rewrite them as this:

// still a method, just one line
private double Tax() => 1.14;
// still a readonly property
public double Price => CostPrice * Tax();
// still a method
private void RaisePain(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

This really cuts the code to statement ratio WAY down and lets you express simple things without much ceremony.

While it uses the => operator, I have intentionally NOT called these lambda’s because they do not support all the functionality of a lambdas.

Supported and Not Supported Scenarios

As we have seen both methods, with or without parameters, and read-only properties (i.e. a property without a setter) are supported. Operators are also supported:

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

nameof is a fantastic piece of syntactic sugar in C# 6, which aims to solve a major pain: magic strings. A magic string is a type of string in your application which is isn’t an input/output related but rather a marker or used for some comparison, for example you might do role checking with something that looks like this:

if (role == "admin")
{
}

The issue with this string “admin”, is that there is NO compiler checking for it. That means if you mistype the content of the string, you do not know it is wrong until the app fails. The second issue with a magic string, is that the refactoring tools do not commonly work with them, so if you changed “admin” to “administrator” in one place, there is no way to tools can find and update all the strings throughout you app and your app breaks again when it runs.

A lot of time you can clean this up with enumerators or objects. For example we can improve our role scenario but checking against an enumerator:

if (role == Roles.admin.ToString())
{
}

This no longer suffers from the two issues listed above

Members & Magic Strings

The problem remains with magic strings which refer to members (fields, properties, methods, types etc…) of your code. In this first example we have a magic string pointing to the property Age:

Note we have eliminated the strings completely! This means if you mistype a member name at compile time you would get an error!

We also get FULL refactoring support now, since Visual Studio and other refactoring tools can get the information they need to identify that it is a member and replace/rename as needed.

More sugar

As mentioned at the start, this is just a case of syntactic sugar, the compiler is doing clever tricks for us and generating slightly different code. All nameof does, is instruct the compiler to convert the member to a string, so the outputted code is the same before with strings.

I want to recommend the TryRosyln website which is FANTASTIC to experiment with C# 6 and also shows you the decompiled code side by side, basically showing you how the syntactic sugar works:

What does it output?

In the first set of examples we looked at simple members, but what if we have something more complex for example a namespace or a class & property. In these cases it will output the last part each time:

nameof(Track.Band); // Class.Property - outputs: Property, in this case 'Band'
nameof(System.Configuration); // Namespace - outputs: Last namespace, in this case 'Configuration'
nameof(List); // List + Generics: outputs: The type of the object, in this case 'List' <
nameof(this.field); // this keyword + field - outputs the field name 'field'

What isn’t supported

nameof isn’t a solution to everything in .NET and there is a lot which won’t work. Here are some examples:

nameof(f()); // where f is a method - you could use nameof(f) instead
nameof(c._Age); // where c is a different class and _Age is private. Nameof can't break accessor rules.
nameof(List<>); // List<> isn't valid C# anyway, so this won't work
nameof(default(List<int>)); // default returns an instance, not a member
nameof(int); // int is a keyword, not a member- you could do nameof(Int32)
nameof(x[2]); // returns an instance using an indexer, so not a member
nameof("hello"); // a string isn't a member
nameof(1+2); // an int isn't a member

Is this a replacement for CallerMemberName?

I have written about a fantastic .NET 4.5 feature called CallerMemberName. To recap it is a way to attribute a parameter of a method and have the runtime change the value of that parameter to be the name of the calling member. In the following example the output will be ‘Main’, matching the name of the calling method:

This seems to be similar to nameof but there are some fundamental differences, most importantly nameof is at COMPILE TIME and CallerMemberName is at RUNTIME. This means that this one method in the example can work with multiple callers; i.e. I could take the above example and have a different member call it and it will output the correct name of the caller. There is no way to do that with nameof, which is basically hard coded values. There is some overlap of functionality and in some cases, like XAML + RaisePropertyChanged where you could pick one or the other based on taste, but these two pieces of functionality do have their differences and there are times where CallerMemberName is the really only option.

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

NULLs, you either hate them or you loath them. They are the source of so many issues in the apps we write, especially the dreaded NullReferenceException. The current fix is to be very defensive in your programming, for example:

NULLET

With C# 6, a new operator has been added; which is officially called the null propagation operator: ?.

Some people have taken to calling it the Elvis operator as it looks like two eyes & a splash of hair similar to Elvis, however I think that hair looks a lot more like a mullet so I have taken to calling this the NULLET operator.

The nullet operator allows us to check for nulls, so we can change the first example to the following which will NOT raise a a null exception:

The way the nullet works, is that it tells .NET to check if the preceding item is null BEFORE moving to the next item. If the item is null, then it stops evaluation at that point and returns null, for example with track:

The important question is what will be the outcome of our above example; if any of the properties are null then it will be “HI!” + NULL which becomes “HI! “ and so that is what will be written to the screen.

Events & Methods

In the first example, there is an example of events and how you need to check for null before raising it. A side note is I am using events as the example, but this applies to any delegate. In the following example you can see how the nullet can help us clean up the event code:

To be able to call the event we need something for the nullet to do after the evaluation, so we use the invoke method. This is also a great example of how the nullet is more than just support properties, it works with methods too.

Null + Indexers = Support for arrays & lists

Nullet can work indexers as well, with a small syntax change – instead of ?., you have just ? (i.e. just a question mark, no trailing full stop). In both scenarios below the code happily executes with NO null issues because we have added the ? between the object and the indexer.

In this scenario, if you have any section as null, it will return a null, however the Enum.Parse method cannot handle null and will raise a NullArgumentException. In this case the method you are passing the null too is key, so you still need to make sure you are checking for nulls in some scenarios, but you can use nullet to make the checking much cleaner:

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

Many of the other C# 6 features I’ve covered are implemented using syntactic sugar, exception filters isn’t. This has been in the deep parts of .NET for some time and in C# 6 it is getting surfaced finally. This is very much the introduction to Exception Filtering, and I have another post with advanced topics I would love for you to read.

Catching Exceptions

Catching exceptions today uses the exceptions type as the condition for the the catch block.

We can catch everything by catching the base Exception class. Order here matters, but the compiler will help prevent you from hurting yourself:

Today, if you want more fine grain control of what a catch block responds to you need to do that in the catch block itself. For example, handling an exception differently based on values in the exception.

Exception Filters

Exception Filters adds a way to have additional requirements for a catch block in the form of a boolean expression which we append with the when keyword. We can now rewrite the two examples as follows:

When isn’t if

Lastly, the language chosen for this feature is important, it isn’t IF, because it isn’t an IF statement – it is a WHEN condition. One of the important distinctions around that is that an IF statement supports ELSE and WHEN does not.

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

Static using statements are a new feature of C# 6 designed to improve the readability of code. Before we begin: a word of warning for this feature. IMHO This feature is not meant to be used everywhere in your code. This feature is like salt, a little is great – too much, can cause issues.

With the warning out of the way, lets see what it does? There are times where the class name can break the flow of the code, lowering readability. Here is some example code we will work with:

Note, that while we have removed the Math class from line 8, we have added a new using statement with the static keyword in line 2. This line tells the compiler where to look if it cannot find the method/property in the current scope. This is just syntactic sugar again and the resulting code is the same as in the first example.

The only requirement for this to work is that the class is that the class is static. That means this works with Math, Console, Convert & any of YOUR own static classes too.

What happens if I have a member with the same name already in scope?

What happens if there is already a member in scope with the same name, for example here I have defined a Cos method:

In this scenario it uses the locally defined member first, as that is the first one which the compiler finds. This is an example of where you can shoot yourself in the foot by using this feature too often and running into hard to find conflicts.

What about Extension Methods?

C# 3.0 added support for extension methods which let you write methods which appear to be part of the underlying class but are actually separate. I’ve added the example method to the string class in the following example:

Adding the static using statement still allows extension methods to be used as normal, however you cannot call the extension method directly this way. If you want to call the extension method directly, you must add the class (& potentially the namespace) in front of the method as you do with C# 5 and before.

using System;
using static ExtensionMethods.Extensions;
internal class StaticUsing
{
public static void BrokenFlow()
{
Console.WriteLine(ExtensionMethods.Extensions.Example("Leslie")); // this works
Console.WriteLine(Example("Robert")); // this does NOT work
Console.WriteLine("Robert".Example()); // this works
}
}

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

A big design trend in C# 6 is the removal of ceremony from code. Ceremony is the amount of code you need to write, to write the code that actually matters. It is the fluff that is there because it is needed by C# and not to solve your problem. Auto-properties are a great example of removal of ceremony & in C# 6 they have been improved further.

In C# 1 we would would type out the full property with the getter & setter and a field. One nice feature is you could initialise the value the field, thus giving the property a default value. For example, like this:

In C# 2 we got the (syntactic sugar) feature for one line properties. The compiler though would generate the field, the getter and the setter automatically in the compiled code. However, the loss of the field, meant the only way to assign a default value was in the constructor, as in the following example:

On one hand, the single line property is great and is an example of less ceremony adding readability, but when we need to assign a default value we add more ceremony and ultimately increase complexity and the potential for errors because there is no obvious way to see the constructor is assigning a value unless you go and check it.

C# 6 simplifies solves this with a new syntax to assign a default value:

In this scenario, the first exception (MyException) is caught and then the second exception is raised. Since there is no try…catch for the second exception, it runs normally and bubbled up until it is either caught higher up or the app crashes. In this example that means an exception of type Exception will be raised.

What if we add a catch all?

As a slight variation, what happens if you add another catch below the first one? Does the second catch, catch the exception raised in the first catch block? For example:

Nope, not at all. It exits the entire try…catch scope and, so that second catch does nothing for what we are testing. In the example above, that means an exception of type Exception will be raised, same as with the first scenario.

Exceptions in When

C# 6 adds the when keyword which allows us to add a filter to our catch blocks. This feature is called Exception Filters & you may find articles using IF as the keyword, but that has changed to WHEN. Prior to C# 6, the condition to run a catch block was just the exception type. Now with C# 6, it is the exception type and, optionally, the result of the when expression. So what happens if the when expression raises an exception? For example:

I assumed it would work in a similar way to the exceptions inside the catch block we looked at above. I was wrong. Any exception in the when condition is swallowed up! In this example, the MyException will be raised since there is no catch block which can handle it as the when has failed due to the exception being raised in test.

What if we add a catch all?

As with the first example, does adding a second catch…block here change the behaviour?

Constant Whens

What happens if the when expression is a constant? Is the compiler smart enough to optimise the code? To work this out I used the AMAZING .NET Reflector which means I can compare the original code, the IL which was generated and the code which was reflected back from the IL.

Starting off with the standard filter, here is what it looks like across places. I suspect the reflected code is showing ? since the version of reflector out currently doesn’t support this.

Let us change the condition to be always true. Thankfully Visual Studio will detect this and warn you:

But what is the result of compiler?

It is pretty much the exact same there, with the filter existing in the IL still :/ Checking with false (and also release builds) shows no difference in any scenario :/

Duplicate whens

The last set of scenarios are around for duplicate when clauses, for example below we have two catch blocks which are the same and I know from running this that only the first one is executed.

Want to learn about other C# 6 features? Check out the full list of articles & source code on GitHub

C# 6 adds in a new feature which is called Dictionary Initialisers or Index Initialisers, because of how they work internally. In fact, the C# team can’t get it straight with roadmap page referring to dictionary while the feature description document, referring to index. While we wait for the name to be decided, what is an index initialiser and how does it work internally?

Note: This is based on VS 2015 CTP 6 and thus may change.

Adding to collections in C# 2

In C# 2 the only way we could add to a collection was with the methods provided by the collection, normally add. For example, below we are adding to a dictionary and an list using the C# 2 way.

Collection Initialisers in C# 3

C# 3 added support for collection initialisers, where we can use braces to add the items. When using collection initialisers, the parentheses for the constructor become optional - for the example below I have omitted them.

This is just syntactic sugar, i.e. the compiler is rewriting this to use the Add method of the collection. In short it ends up the same as the example above when it is run - it is just easier and less error prone to type using collection initialisers.

In the above example you’ll note that we use similar syntax to the collection initialiser (use of brace, optional use of constructor parenthesis) but the way we add items is different. We use brackets to define the index, followed by equals and the value. Internally this is different to collection initialisers since the generated code does NOT use the add method, rather it uses the collections indexer. For example, this is what the generated code the above index initialiser example would look like:

Since the compiler is generating code with indexers, the ONLY requirement for the class being added is that the class it must have an indexer and the indexer has which has a setter method. This means it can be used on anything which supports indexers. There is NO requirement that this can only be used with collections or things which support IEnumerable.

Example non-collection usage

As mentioned this can be used outside a collection, so let us build a bit of code to assign the four roles to a team.

NOTE: This is an example, it is not meant as guidance for how you should do it. Personally, I think the end example is better handled by a constructor.

In C# 2 we may have done it like this:

public static void C_Sharp_Two_Set_Members()
{
// code to add team members
var team = new Team();
team.ScrumMaster = new Member("Jim");
team.ProjectOwner = new Member("Sam");
team.DevLead = new Member("Phil");
team.Dev = new Member("Scott");
}
// we will exclude role from future examples since it doesn't change in the other examples
enum Role
{
ScrumMaster,
ProjectOwner,
DevLead,
Dev
}
class Team
{
public Member ScrumMaster { get; set; }
public Member ProjectOwner { get; set; }
public Member DevLead { get; set; }
public Member Dev { get; set; }
}

// we will exclude member from future examples since it doesn’t change in the other examples
class Member
{
public Member(string name)
{
Name = name;
}
public string Name { get; }
}

With C# 3 we could change this to use an object initialiser, which ultimately generates the exact same code as in C# 2:

The one requirement for both examples is that the properties have accessible setter methods, or it will not work, so we cannot use either option with private setters for example. We could use an indexer in this scenario by adding it to the Team class and then being able to use Index initialiser syntax to assign the roles.