-6

I am using a simple error handling and I think I have everything else right, how would I make the if statement check to see if the value is equal to this array?

String[] values = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };

public String Value
{
    get
    {
        return _value;
    }

    set
    {
        if (value != values)
            throw new Exception("Invalid Card Value");
        _value = value;
    }
}
craftomega
  • 21
  • 2
  • Do you want to see if the given value is *in* the array? – siride Dec 01 '14 at 19:08
  • 2
    "how would I make the if statement check to see if the Value is equal to this array?", `Value` is of type string, it can never be equal to string array, instead you should search, if the `Value` is contained in the array like `if(!values.Contain(value)) throw new Exception....` – Habib Dec 01 '14 at 19:09
  • 1
    Side note - throwing a vanilla Exception in the setter seems like a bad idea. The caller then has to check the message to know how to properly handle the exception. Either throw a custom exception that the client can catch and handle specifically or do validation at a higher level. – D Stanley Dec 01 '14 at 19:12
  • @DStanley especially considering how easy it is to do a simple extension of Exception. – Phylogenesis Dec 01 '14 at 19:13
  • @DStanley: there's also ArgumentException or ArgumentOutOfRangeException, which are descriptive enough. – siride Dec 01 '14 at 19:14

1 Answers1

4

You can't just compare a string to an array of strings to find out if it exists in the array. You can use the Contains method to loop through the array and look for the value:

        set
        {
            if (!values.Contains(value)) {
                throw new Exception("Invalid Card Value");
            }
            _value = value;
        }

If you do this a lot, you could consider to put the strings in a HashSet<string> instead of an array. It's faster to check if a value exists in a hash set than an array.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer. – Guffa Dec 01 '14 at 21:12