Fixits are small posts that provide a straight forward answer for issues that occur during development.
Recently, I tried to fire up a project that previously builds like a fresh pie coming out of the oven, instead my project caught on fire.
It used the Device.OnPlatform function which has been obsoleted. This article shows you how to fix this.
Your Xamarin cross-platform app builds as a charm with code to check what platform you’re on.
The project is throwing the following error in your face:
[crayon-5bca964f587af352530557/] Want to know how to fix this? Check it out after the break.
In my case the project was using the OnPlatform function in line to set the correct font size, depending on the platform the app was being built for.
As you can see in the function’s documentation at Xamarin’s website the function could previously be used to set a value for a variable, depending on the platform.
[crayon-5bca964f587c3414466571/] This would give back the size 16 for iOS and Android or 18 for Windows Phone.
Using a switch is what is suggested by the obsolete hint:
[crayon-5bca964f587e0678719872/] What’s up with the code foodprint increase?
As you can read in the discussion on the xamarin forum they’re favouring the switch aproach over the OnPlatform to make it more extendable. Wearables and Operating Systems are going to become more diverse and they want to prepare for an expanding array of platforms. Switch statements are flexible since they can have numerous case options compared to a parameterized function. Plus, they are clearer to read.
The solution I showed above was nice, but what if HeaderFontSize was being used as a parameter for a font function inside a static class and you’re not able to / don’t want to define parameters to hold the size?
Well, you could use a ternary expression to keep things simple… For example:
[crayon-5bca964f587eb978166471/] Would become:
[crayon-5bca964f587fd663127101/] PS: I know that not everyone likes the syntax of a ternary function, but in order to prevent using temporary variables and keep it a “one-liner” it sure as hell is the shortest thing I found to use and replace any similar code with and prevent the code from blowing up over multiple lines.
Hope this helps you update your Xamarin project to build once more and become a more flexible and expandable solution.
Let me know in the comments below if you had similar experiences or have another approach on how to fix this