Ryan Bishop
Ryan Bishop

Reputation: 3

Create class and choose from list of constants

I'm trying to define a class and one of the parameters I would like to pull from a finite list of constants that acts sort of like a dictionary. I'm not really sure what to call this or search for, but I think I've seen some built in classes use this.

The reason for this is that the API I'm using needs this class to be built a certain way and uses a lot of numbers that don't make readable sense. I'd rather create the object using the meaningful word than the ID number it goes with.

Example: Contains = 2, Does not contain = 5, Greater than = 3, less than = 4 etc.

TestClass foo = new TestClass (CONTAINS, "hello world");

I'd like this to operate sort of like a dictionary, so that the rest of the code treats the first parameter as '2' and not the string "CONTAINS"

Am I out of my mind or is this possible? Thanks!

Upvotes: 0

Views: 52

Answers (1)

This is an enum. You can let the compiler assign arbitrary numeric values if you like:

public enum MyOperator {
    Contains,
    DoesNotContain,
    GreaterThan,
    LessThan
}

public class TestClass {
    public TestClass(MyOperator op, Object operand) {
        this.Operator = op;
        this.Operand = operand;
    }

    public MyOperator Operator { get; set; }
    public Object Operand { get; set; }

You can specify the numeric values if you have some reason to:

public enum MyOperator {
    Contains = 2,
    DoesNotContain = 5,
    GreaterThan = 3,
    LessThan = 4
}

And explicitly cast:

int x = (int)MyOperator.LessThan;

Also stringify:

public void F(MyOperator op) {
    MessageBox.Show(op.ToString());
}

Maybe Operand should be string, or maybe the whole thing should be generic, but you didn't say. It's an example.

Upvotes: 2

Related Questions