Pass Permissiion to a Class

Jassim Al Rahma 1,556 Reputation points
2021-09-03T22:52:53.857+00:00

Hi,

I am trying below code to pass a Permission as parameter so I can use it this way:

CheckAndRequestPermission(Permissions.Photo);

but getting this error:

Error CS0721: 'Permissions': static types cannot be used as parameters

using System;
using System.Threading.Tasks;
using Xamarin.Essentials;

namespace MyApp
{
    public class PermissionCheck
    {
        public async Task<PermissionStatus> CheckAndRequestPermission(Permissions permission)
        {
            var status = await Permissions.CheckStatusAsync<Permissions.Photos>();

            if (status == PermissionStatus.Granted) return status;

            if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
            {
                status = await Permissions.RequestAsync<Permissions.Photos>();

                return status;
            }

            if (Permissions.ShouldShowRationale<Permissions.Photos>())
            {
                status = await Permissions.RequestAsync<Permissions.Photos>();

                return status;
            }

            status = await Permissions.RequestAsync<Permissions.Photos>();

            return status;
        }
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,141 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 114.7K Reputation points
    2021-09-04T04:21:01.747+00:00

    Try something like this:

    public async Task<PermissionStatus> CheckAndRequestPermission<P>( ) where P : BasePermission, new()
    {
       var status = await Permissions.CheckStatusAsync<P>();
    
       . . .  use <P> instead of <Permissions.Photos>
    }
    

    Usage: CheckAndRequestPermission<Permissions.Photos>( ).

    1 person found this answer helpful.
    0 comments No comments

  2. P a u l 10,496 Reputation points
    2021-09-03T23:09:17.343+00:00

    Permissions.Photos looks like it's a BasePlatformPermission/BasePermission from what I'm seeing in the Xamarin.Essentials repo, so you could try switching your CheckAndRequestPermission method to accept one of those instead. The Permissions type is static so you wouldn't be able to pass in an instance like you are atm.

    0 comments No comments