Jan
Jan

Reputation: 2168

Create a custom selection of parameters

I have a method that requires a parameter to distinguish between a few different scenarios. I could just pass on a string and hope that I (or whoever will use the class in future) will use one of the recognized commands. I would rather have a construct like this:

method declaration:

myMethod(myOption opt){ ... }

and the call should look like:

myMethod(myOption.option1);

in the method I should be able to do this:

if (opt == myOption.option1){ ... }

I believe this is the way the Message Box works, when I pass on the button or icon configuration.

I have experimented a lot and searched a lot, but I didn't find anything. Maybe that is because I have not found the correct combination of keywords to feed to google.

Thanks for your help!

Upvotes: 0

Views: 128

Answers (1)

RJ Lohan
RJ Lohan

Reputation: 6527

If you have a restricted set of available parameters, then an enum is probably the most suitable argument type to your method. So, create an enum to pass as your parameter;

public enum MyOption
{
    Option1,
    Option2,
    Option3,
}

public void MyMethod(MyOption option)
{
    switch (option)
    {
        case MyOption.Option1:
            // do stuff
            return;
        case MyOption.Option2:
            // do stuff
            return;
        case MyOption.Option3:
            // do stuff
            return;
    }
}

Upvotes: 6

Related Questions