0

My partial class didn't targeting the #if in Xamarin Forms project with NETStandard 2.0

A sample of the problem is:

     public partial class App : Application
       {
       #region StaticString
        #if __IOS__
        public static String A
        #endif
        #if __ANDROID__
        public static String A
        #endif
        #if WINDOWS_UWP
        public static String A;         
        #endif
       #endregion

     public App ()
           {
            InitializeComponent();
            InitializeApplication();

           #region Teste
            #if __IOS__
            A="ios";
            #endif
            #if __ANDROID__
            A="droid";
            #endif
            #if WINDOWS_UWP
            A="UWP;         
            #endif
          #endregion
          }

        }

I need to acess and send specific code for my viewmodels but it was unable and invisible for another class (like this String A).

I saw a sample/way in "Accessing Native Views in Code"

Is it only work in Shared Code ?

Regards

  • 1
    The code you are using for your platform conditions is used in Shared projects use Device.OnPlatform instead – FreakyAli Aug 28 '18 at 14:16
  • #if is a COMPILER directive, and the compiler does not know what the runtime platform is – Jason Aug 28 '18 at 14:17
  • Like this ? switch(Device.RuntimePlatform) { case Device.iOS: A="ios"; break; case Device.UWP: A="UWP"; break; default: A="android" break; } – Guilherme Marques Aug 28 '18 at 14:22

1 Answers1

2

The compiler directives are only available in shared code and Device.OnPlatform is deprecated. The solution for this is to use Device.RuntimePlatform in a switch statement. This would make your code look something like:

public static string A;
switch (Device.RuntimePlatform)
{
    case Device.iOS:
        A = "ios";
        break;
    case Device.Android:
        A = "droid";
        break;
    case Device.UWP:
        A = "UWP";
        break;
    default:
        A = "unknown";
        break;
}

Take a look at the Microsoft docs for information on using Device.RuntimePlatform

Andrew
  • 1,390
  • 10
  • 21