Search code examples
.netportable-class-library

Can I limit a class or method in a Portable Class Library to a specific platform?


I'm creating a Portable Class Library and Targeting .Net 4.5, Windows 8, Windows Phone 8.1 and Windows Phone Silverlight 8.

Can I limit a class or method to a specific target? Like a method can only be called from a .Net 4.5 project, and not from a Windows Phone 8.1 project.

Is this possible?


Solution

  • Yes, by using directives that specify those platforms. Now I'm not entirely sure if there is a .NET 4.5 directive automatically available but as far as I know there are the

    #SILVERLIGHT, #WINDOWS_PHONE, #WP8 and #NETFX_CORE directives available.

    You can use them like this:

    #if WINDOWS_PHONE
       int x = 1;
    # else
       int x = 2;
    #endif
    

    In your situation you would place them around the method so the method would only get compiled if the right projects are targetted.

    I believe #NETFX_CORE only indicates it is Windows 8 and not .NET. There might be .NET specific directives but they aren't set automatically for the projects you're referring to (probably because those use WinRT, not .NET per sé).

    However this answer indicates that you could set it with a custom directive:

    <DefineConstants Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">
        RUNNING_ON_4
    </DefineConstants>