Home > OS >  Complier error if function parameter string is not in allow list
Complier error if function parameter string is not in allow list

Time:09-27

I was wondering is there is some C#\Visual Studio magic where I can have a list of strings that form a allow list for parameter inputs into a function?

In other words I would have a list of strings [“Green”, “yellow”, “blue”] and a function void example(string colour);. If I try to do example("red"); I get a complier error.

Bonus point if I can read this list for a text file or something, but copy and paste is fine.

Thanks

EDIT: I have ended up using const string C_RED = "RED". I never noticed that intellisence will give you a list of const. This works well as I can just type C_ and it will give me the valid options.

CodePudding user response:

Store the string in the list collection. Then take out the corresponding value and pass it to the example method.

  static void Main(string[] args)
    {
        List<string> mList = new List<string>(){"Green", "Rellow", "blue"};

        mList.Add("Green");
        mList.Add("Rellow");
        mList.Add("blue");
        new Program().example(mList[2]);

    }

   
    public void example(string colour)
    {
        Console.WriteLine("colour:"   colour);
    }

Hope it helps you.

CodePudding user response:

A analogy of the problem I faced and this is how I addressed it. I want to restrict the Action in a Controller to be executed only if the query parameters in the request has allowed values.

1. Created a custom Validation Attribute

public class ElementValidate : ValidationAttribute
    {
        public string[] element = { "GREEN","YELLOW","BLUE" };

        public override bool IsValid(object? value)
        {
           string user_input =  (value as string).ToUpper();
            if (element.Contains(user_input))
            { 
                  return true;
            }
            else
                return false;   

        }
    }

2. Place the Attribute over the action method for which it is to be checked.

   [ElementValidate]
    public void Sample1()
    {
      // Actual Logic Goes Here
    }

CodePudding user response:

Try this

enum colors {Green=1, yellow=2, blue=3};

void example(string colour)
        {
            //Convert month in enum;
            Enum.TryParse(colour, out colors givenColour);

            if (givenColour == 0)
                throw new Exception("Invalid colur");

            // your implementation
        }

enter image description here

  • Related