How can I set defined values for a parameter? I mean, for example, I have the following function:
int functionA(string parameterA) {}
Now, when I call this function and input value for the parameterA, I want the value to be in the value set I have defined. For example, the defined value set is:
string[] definedParameterA = { "Hello World", "stackoverflow" };
the value of parameterA I input must be “Hello World” or “stackoverflow”.
If you really want it to be a string, you’d just validate it at the start of the method:
However, you might also consider using an enum instead. You still need to validate that the enum value is defined, but it makes it simpler for the caller to get it right:
You can have a mapping from the enum value to string elsewhere if you want, of course.
Note that the above code will box
messageon every call. You could avoid that (and make it more typesafe) using my Unconstrained Melody project if you really want, but it’s probably not worth it until you’ve proved that this boxing is actually an issue. The code would then look like this: