How can I pass an attribute parameter type with List<string> in C#?

The problem isn't passing a List<string> to a constructor in general - the problem is that you're trying to use it for an attribute. You basically can't do that, because it's not a compile-time constant.

It looks like ProgramList is effectively an enum - so you might want to make it an enum instead:

 [Flags]
 public enum ProgramLists
 {
     SurveyInput,
     SurveyOutput,
     ...
 }

Then make your CustomAuthorizeAttribute (which should be named like that, with a suffix of Attribute) accept a ProgramLists in the constructor. You'd specify it as:

[CustomAuthorize(ProgramLists.SurveyInput | ProgramLists.SurveyOutput)]

You can then have a separate way of mapping each ProgramLists element to a string such as "A001". This could be done by applying an attribute to each element, or maybe having a Dictionary<ProgramLists, string> somewhere.

If you really want to keep using strings like this, you could make CustomAuthorizeAttribute accept a single comma-separated list, or make it an array instead of a list and use a parameter array:

[AttributeUsage(AttributeTargets.Method)]
public class FooAttribute : Attribute
{
    public FooAttribute(params string[] values)
    {
        ...
    }
}

[Foo("a", "b")]
static void SomeMethod()
{
}

You can't use List<T>.

Attributes have restrictions on parameters and property types, because they have to be available at compile-time. Using attributes in C#

Use an array instead:

//constructor
public CustomAuthorize(string[] _multipleProgramID) 
{
    ...
}

// usage
[CustomAuthorize(new string[] { ProgramList.SURVEY_INPUT, ProgramList.SURVEY_OUTPUT })]

I was trying to do something similar and ended up passing a comma separated string and using string.Spilt(',') in the attribute constructor to convert it to an array.

Tags:

C#

Asp.Net Mvc