0

I want to be able to allow only certain values to a custom object method. The first example that came to mind to illustrate the point is the VB msgbox and the specific values that you use for which set of buttons you could choose.

 MsgBox("Message", vbYesNo,"title")

How would I be able to do the same in C# with a custom object?

The method will search a particular area based on the value sent.

 object.method(SearchArea1);
 object.method(SearchArea2);

I want to be able just type SearchArea1 or SearchArea2 (not as strings) just like you would use vbYesNo, vbCancel.

Does that make sense at all?

1

2 Answers 2

3

You could define an enum and then use it as parameter for method

public enum SearchArea 
{
    SearchArea1,
    SearchArea2
}

public void method(SearchArea searchArea) 
{
    switch (searchArea)
    {
        case SearchArea.SearchArea1:
            // your logic for SearchArea1
            break;
        case SearchArea.SearchArea2:
            // your logic for SearchArea2
            break;
        default:
            throw new ArgumentException("Logic not implemented for provided search area");
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

The else isn't the best way to do that because it makes the code kind of brittle. If he adds future enum values, they'd all fall to the else. A switch would be better with an exception in the default case so it will be immediately obvious after future refactorings if he forgot to modify the logic in method to deal with the new enum value(s).
@roryap: agreed, it was a simple method template to show how to use the enum. It's true that better to do it right though, thanks.
A break after a thrown exception will be unreachable and could be removed.
Thanks guys! I new it would be simple!
So a quick follow up question: What's the difference between using enums rather than just creating properties? From what I read it's more a code manageability thing than performance?
|
0

What you're looking for is called an enumeration.

1 Comment

Thanks everyone! I figured it was easy. I just wasn't sure what to google!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.