Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial platform specific methods in .NET MAUI

I'm trying to implement plattform specific partial method in .NET MAUI to get the connection string for the database.

In the "main application":

namespace TestApp.DL;

public partial class BaseHandler
{
    public partial string GetDBPath();

    private string GetCnnPath() 
    {
        var dbPath = GetDBPath();
        var cnnPath = $"Data Source={dbPath}";

        return cnnPath;
    }

    ...
}

in the platform folders in the project:

enter image description here

where each contain the plattform specific implementation:

namespace TestApp.DL;

// All the code in this file is only included on Android.
public partial class BaseHandler
{
    public string GetDBPath()
    {
        var dbName = "com.mycompany.mydatabase.db";
        return Android.App.Application.Context.GetDatabasePath(dbName).AbsolutePath;
    }
}

...but I keep getting "Error CS8795: Partial method 'BaseHandler.GetDBPath()' must have an implementation part because it has accessibility modifiers. (CS8795)". It seems like the platform specific files are not seen by the compiler? Note, they are in a separate assembly project from the main application but that should be ok I guess, given that the fwk created the folders for me?

like image 892
Cliffhanger Avatar asked Oct 17 '25 02:10

Cliffhanger


1 Answers

When you struggle with partials you can keep using partial classes, but avoid using partial methods. This is especially true when creating maui libs, where this approach tends to break, while in maui apps the compilation works fine.

The "quick fix solution", all partial classes must use same namespace obviously:

Shared code, you would want to change NET6_0 to NET7_0 whatever you are using:

public partial class BaseHandler
{
    private string GetCnnPath() 
    {
        var dbPath = GetDBPath();
        var cnnPath = $"Data Source={dbPath}";

        return cnnPath;
    }

#if (NET6_0 && !ANDROID && !IOS && !MACCATALYST && !WINDOWS && !TIZEN)

        public string GetDBPath()
        {
            throw new PlatformNotSupportedException();
        }
#endif
}

Your platform specific code in platform Platforms/Android:

public partial class BaseHandler
{
    public string GetDBPath()
    {
        var dbName = "com.mycompany.mydatabase.db";
        return Android.App.Application.Context.GetDatabasePath(dbName).AbsolutePath;
    }
}
like image 69
Nick Kovalsky Avatar answered Oct 20 '25 00:10

Nick Kovalsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!