Code Improvements With Unity 2017.1 & C# 6
One of my favorite features of Unity 2017.1 is the (experimental) update to the supported C# language version to C# 6. While there isnât any single feature that will drastically change the way I program, there are a few features that can simplify your code and I thought Iâd share some examples.
First off you need to enable the correct language version by switching your scripting runtime to âExperimental (.NET 4.6 Equivalent).â This will require an editor restart, and then youâll be ready to go!
String Interpolation
String interpolation is a simple syntax addition to make creating strings from data a bit easier. Previously if you wanted to create a string that contained some variable data youâd end up doing something like:Â
With string interpolation you can change this to:
Or you could even simplify it further to:
Null Conditional
Sometimes when you need to pull data out of an object hierarchy it can end up looking something like this:
This is a made up example to belabor the point, but you get the idea. Checking for null at each step in the chain and exiting, to prevent hitting a null pointer exception. With C# 6â˛s null conditional operator, instead you can simply do this:
The â?â after each step in the access chain says âif this is null exit the chain early and set prefabName2 to null, otherwise keep going.â
Index Initializers
So for a while weâve been able to initialize a list with pre-set values, like so:Â
which is great, right? This syntax also works for dictionaries:
works great, and should work for any class that implements IEnumerable and has an appropriate Add() method to add new elements.
C# 6 adds a new option called an Index Initializer. Instead of relying on IEnumerable and Add(), it uses indexing behind the scenes to set values. Our dictionary would now look like this:Â
This syntax should work for anything that has a custom indexer. For simpler cases like a generic Dictionary, youâre probably fine just using whichever syntax you prefer.
Hey, what about async/await?
Thatâs a fair question, but I havenât had enough time to play with them within the context of unity to say much about them. Once I get some more time Iâll make a new post!

















