Accessing native features with DependencyService

Download xamarin.forms eBook

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.

Related Examples

Stats

224 Contributors: 4
Friday, July 29, 2016
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook