Search code examples
c#enums

Pass in an enum as a method parameter


I have declared an enum:

public enum SupportedPermissions
{
    basic,
    repository,
    both
}

I also have a POCO like this:

public class File
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public SupportedPermissions SupportedPermissions { get; set; }      
}

Now I would like to create a method that I can use to create a new File object with:

public string CreateFile(string id, string name, string description, Enum supportedPermissions)
{
    file = new File
    {  
        Name = name,
        Id = id,
        Description = description,
        SupportedPermissions = supportedPermissions.basic
    };

    return file.Id;
}

How would I create the parameter for the enum and how would I assign that like in my pseudo code SupportedPermissions = supportedPermissions.basic so that my File instance has a SupportedPermissions set to it?


Solution

  • Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum.

    public string CreateFile(string id, string name, string description, SupportedPermissions supportedPermissions)
    {
        file = new File
        {  
            Name = name,
            Id = id,
            Description = description,
            SupportedPermissions = supportedPermissions
        };
    
        return file.Id;
    }
    

    Then when you call your method you pass the SupportedPermissions value to your method

      var basicFile = CreateFile(myId, myName, myDescription, SupportedPermissions.basic);