Xamarin.Forms Accessing native features with DependencyService

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

If you do not want your code to break when no implementation is found, check the DependencyService first if it has a implementation available.

You can do this by a simple check if it is not null.

var speaker = DependencyService.Get<ITextToSpeech>();

if (speaker != null)
{
    speaker.Speak("Ready for action!");
}

or, if your IDE supports C# 6, with null-conditional operator:

var speaker = DependencyService.Get<ITextToSpeech>();

speaker?.Speak("Ready for action!");

If you don't do this and no implementation is found at runtime, your code will generate an exception.



Got any Xamarin.Forms Question?