Even when developing a cross-platform Xamarin.Forms app, you still often need to write some platform-specific code to get the most out of each platform. Apart from analyzing Xamarin.Forms Xaml code, the latest version of XamRight also introduces error checking for Xamarin.Android and Xamarin.iOS C# code. Here we will look at some of the common errors made when building platform specific code using Xamarin (even if you’re not using Forms) and how XamRight helps.
Xamarin.iOS
One common mistake made when writing Xamarin.iOS code is the incorrect spelling or casing of the property key string value when trying to hook up the AddObserver method as described in a previous blog post – Key Value Observing on iOS for Xamarin. As stated in the post the key value string used in the AddObserver method has to match the export attribute of the getter of the property that is being observed. XamRight’s analyzer does this check for you.
Xamarin.Android
An ArrayAdapter in Xamarin.Android is an array of objects most often used to populate Android ListViews. Using an ArrayAdapter can be a little tricky for beginners. The default implementation of an ArrayAdapter expects the provided resource id which is the second argument of the ArrayAdapter to point to a single TexView or a wrapper layout that contains a TextView. Each list item would use the TextView to present its data as a string value (you can however, extend the ArrayAdapter class as a work around if more complex views are needed for your ListView). Because errors to the layout ids used for ArrayAdapters are not caught until runtime, XamRight parses the layout provided and validates that it is a TextView or contains a TextView. ListView cells can’t be of type ListView, so XamRight checks that the cell layout is not of type ListView or contains a ListView.
Another bug often run into by junior Android developers is to try to call FindViewById before SetContentView is called when presenting an Android Activity. The flow-sensitive analyzer in XamRight catches these bugs to prevent runtime errors.