Xamarin.FormsAccessing native features with DependencyService


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.

Related Examples

Getting Application and Device OS Version Numbers - Android & iOS - PCL