July 28 2020
Continuing with our Modern C# for Unity Game Development series, today I’m going to show you how to reduce the verbosity of your code with C# Expression-Bodied Members.
Note: this might upset some verbosity lovers out there 😏
Imagine you want to keep your player data synchronized with a server.
(Such a rare scenario, right?)
So you create your user manager class that does a GET request to update some fields.
Basically, you ask your backend for information on the a player ID. With that new information, you update your UI, gameplay elements and so on.
Here’s a simplified code snippet that does this update:
public class UserDataProvider
{
private string UrlUserInfo
{
get { return $"https://mygame.api/user/{_userData.userId}"; }
}
UserDataProvider(string userId)
{
_userData = new UserData(userId);
}
void Start()
{
CoroutineManager.StartCoroutine(RefreshUserInfo());
}
IEnumerator RefreshUserInfo()
{
var request = UnityWebRequest.Get(UrlUserInfo);
yield return request.SendWebRequest();
_userData.name = ParseJson(request.downloadHandler.text, "name");
// ...
}
}
So, what’s the problem with that?
You see, verbosity is my problem.
Sure, it looks quite normal if you’re used to it… (I got pretty used to this code-writing style myself).
However, there’s BIG room for improvement…
And today, we will be concerned with two questions:
A very standard-driven, verbosity-lover programmer will tell you that you need all of it.
But me, as a programmer who reads thousands of line of code per day, I’ll buy into anything that:
And today I’m showing you the tool that will let you achieve all of this.
Expression-bodied members is just one of these fancy terms that are easier to understand by reading code than by trying to decipher its name.
Put simply: this C# feature lets you remove verbosity when dealing with single expressions.
That means:
We gain this simplicity by skipping certain language elements (such as curly braces) and introducing the => operator.
No worries, reading actual code will make it much easier to understand.
Remember that getter and the functions?
Well, have a second look now:
private string UrlUserInfo => $"http://mygame.api/user/{_userData.userId}";
UserDataProvider(string userId) => _userData = new UserData(userId);
void Start() => StartCoroutine(RefreshUserInfo());
By using expression-bodied members I simplified my code so that…
We got rid of curly braces… and the return + get keywords.
And I could go on with more examples, but you get the idea.
You can apply this technique as well to finalizers (destructors) and setters.
Here’s one last example before I go:
private UserData _userData;
public UserData MyUserData
{
get => _userData;
set => _userData = value ?? _userData;
}
Neat!
If you’re wondering what else you can learn today to substantially improve your game, have a look at my tutorial on improving your game memory and loading times.
Alright, talk to you soon!
~Ruben