Bill Wagner creates C# learning and reference materials for https://learn.microsoft.com. He works with colleagues on the C# team, related content teams, and customers to provide resources for everyone that wants to learn more about C#. He’s also a member of the ECMA C# Standardization committee, working to update the C# standard.
I asked Bill, to come talk about C# 11 and to do so from the perspective of a programmer who stopped following the newest additions to C# as of C# 7 or 8 or so. That is, how do we catch up if we’ve fallen behind on the latest features?
Building on the previous postings, today I want to discuss the magic of Dependency Injection (DI)
Dependency Injection makes for cleaner and more testable code. We’ll get into testing and Mocks in a later blog post, but using DI allows you to substitute a mock service for a real one. In any case, it is magical.
Even though this is powerful, this posting will be short, because once you know how to do it, it is very easy.
Let’s look at BuddyPreferences. This is the page that lists all the preferences of a specific buddy. We start, in BuddyPreferences.xaml.cs by creating BuddyPreferencesViewModel so that it can be our BindingContext. We pass the ViewModel into the constructor. Here is the complete class:
public partial class BuddyPreferences : ContentPage
private BuddyPreferencesViewModel vm;
public BuddyPreferences(BuddyPreferencesViewModel vm)
this.vm = vm;
BindingContext = vm;
In the previous postings we looked at creating the basic app and adding a single, simple page. This post will really begin to get into it.
We’re going to have a number of pages
A page for you to enter your own preferences
One for looking at your buddy list
One for look at your buddy’s preferences
A page for inviting someone to become your buddy
Each of these pages will have its own viewmodel class. We’ll also need services to talk to the API client (e.g., BuddyService with methods to get your buddy list, add to your list, see your buddy’s preferences, etc.)