ZakFS ZakFS - 17 days ago 7
C# Question

Add platform specific codes to a Portable Class Library

Hi I'm trying to create a NoSQL Database that would work on Android, UWP and IOS to use for my own project and to publish on nuget for others.

So I need to be able to create, delete, write and read files on all of these platforms.

I'm looking for a way to do all of this platform specific coding in the PCL itself or a link to a source that explains how to make and publish a portable-friendly API or simply how to write platform specific codes in the portable class itself.

btw i've already tried to use the #if UWP #endif and made a test project but since it's a portable class library it just ignores it when it runs.

example:

public void CreateFile(string path) {
if (Platform == UWP) {

}
if (Platform == Android) {
//Create file for UWP
}
if (Platform == IOS) {
//Create file for UWP
}
}

Answer

If you have specific code for each platform then you could use the Bait & Switch trick to perform this, that is the approach used in many of the Plugins of Xamarin.

Basically, you create an Abstractions project and an implementation project of PCL where you have the interface and class, respectively, that you will use to do the calls (and of course a singleton or something that creates the aforementioned class calling simply new Class()).

Then in each platform specific project you implement the abstraction defined in the abstraction project maintaining the SAME namespace and class name as the one defined in the PCL implementation and it's done.

Finally you create your nuget and you're set to go.

I suggest you look at the link, which is from James Montemagno and explains this.

Comments