Issues with certain libraries included for specific frameworks

Manickam, Suraj 280 Reputation points
2024-06-26T09:34:46.0866667+00:00

We have certain nuget packages available for different target frameworks either Android or IOS or just .net8.0 ,this is controlled via csproj , Is there any better way to let my .cs files know that it has to build only for this target frameworks other than mentioning #if ANDROID or #if IOS in different files ? I do have a lot of files and adding if condition can be a bit more overhead to me.

MAUI version : 8.0

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,115 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 38,066 Reputation points Microsoft Vendor
    2024-06-27T06:01:12.4333333+00:00

    Hello,

    You can use the following code to specify the platform for Nuget Package in the csproj file, but you need to refer to it in the MAUI project using conditional compilation.

    
    <ItemGroup Condition="$(TargetFramework.Contains('-android'))">
    
    	<PackageReference Include="" Version="" />
    
    </ItemGroup>
    
    

    This is because conditional compilation is meant to mask the behavior of the compiler, which needs declarations to know where to compile under what circumstances.

    For example by the above code an Android and iOS Package is declared separately and the target framework of the program is .net8.0-android. Then when using the iOS code block you will get a Not Available error. If you add #if IOS to make the declaration, the compiler can realize that this code does not need to be compiled in the Android framework.

    If you don't want to use conditional compilation, you could wrap these features into a cross-platform API, as suggested by the official documentation.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments