Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific values as argument for function

Tags:

c#

asp.net

I've got a function which has 1 parameter/argument of type String:

        public void foo(String myParam)
        {
           //do something
        }

the possible values of the string are restricted (eg. "test","test2" and "test3"), any different value of myParam would cause an error.

Is it possible to restrict the possible values of myParam without a switch case which would check the value of myParam?

It would also be possible to pass a different object to my function which wraps the real value I need.

Is there a standard/best way solution for that?

like image 490
Zteve Avatar asked Jul 30 '26 18:07

Zteve


1 Answers

You could create an enum

public enum MyParam
{
    test,
    test2,
    test3
}

And use ToString to get the string representation of your enum

public void foo(MyParam myParam)
{
    if(!Enum.IsDefined(typeof(MyParam),myParam))
        throw new ArgumentException();
    myParamString = myParam.ToString();
}
like image 192
juharr Avatar answered Aug 01 '26 07:08

juharr