Reputation: 4032
I have a lookup table with an id and a text value.
What is the best way to check if a value is x or y? Hardcoding the string? Using an "enum"?
EDIT: What I mean is, is it ok to just do:
if (VALUE_FROM_DATABASE == "value x")
then do this
What if the values in the database change in the future? I guess there might not be a way around that and we'll always have to change the code when that happens?
Upvotes: 1
Views: 796
Reputation: 6146
store that string on the configuration
if (VALUE_FROM_DATABASE == ValueFromConfig) //...then do this
Upvotes: 0
Reputation: 57169
Possibly you mean that your database lookup table has, say, enum-style values "In store|Out of stock|Unavailable". If you want to use enums in your code, you have to jump through some hoops:
Original answer, possibly void after edit of OP:
Something like:
// get your value from the database (don't know what you use now):
string value = lookupTable.GetById(12345).Text;
if(value == "x" || value == "y")
{
// do your thing
}
But then I'm assuming a lot about your current code, of which you don't show much.
EDIT: you ask whether you should change your code when your database's value changes. No, not needed. Each time your run your code, you retrieve the value from your database, and there won't be a problem.
Upvotes: 0
Reputation: 1200
There is an Equals method on strings that you should use for comparison so something like
if(value.Equals(stringToCompareTo)){}
There is an overload to that method which takes a value from the StringComparison
enum so if you wanted to ignore the case in your comparison you would do something like
if(value.Equals(stringToCompareTo,StringComparison.OrdinalIgnoreCase)){}
Upvotes: 0
Reputation: 101166
it depends on how many different values you are comparing with. If one or two, then go a head and use an if statement and the equal sign.
Do not use lots of if
statements. It might be better to use a switch
statement then or a Dictionary
to find acceptable values.
Upvotes: 0
Reputation: 7856
I tend to put a SystemId
value on any lookup table on which change the way the program works, and then create a matching enum
to reference it in code (although if I'm using NHibernate, I just use the enum). If I were to be completely paranoid strict, I'd create a check constraint and a unique on the SystemId column too to stop anyone adding anything to it without really having to try hard.
Upvotes: 0
Reputation: 81680
If you have a lookup table and you are reading the values from a table, etc you cannot use switch
statement since it must be a constant
.
Upvotes: 0
Reputation: 2005
just use simple if:
if(value=="myString") {}
I do not see here a reason for Enum
Upvotes: 1