tags:

views:

90

answers:

3

I just wonder how to write a number that has to be expressed as string.

For instance:

if (SelectedItem.Value == 0.ToString()) ...

or

if (SelectedItem.Value == "0") ...

or

public const string ZeroNumber = "0";
if (SelectedItem.Value == _zeroNumber) ...

or

if (Int.Parse(SelectedItem.Value) == 0)
+8  A: 

For a single test, I'd personally go with

if (SelectedItem.Value == "0")

It has no fuss, no ceremony - it says exactly what you're trying to do.

On the other hand, if I have a value which should be a number, and then I'll react based on that number, I'd use:

int value;
// Possibly use the invariant culture here; it depends on the situation
if (!int.TryParse(SelectedItem.Value, out value))
{
    // Throw exception or whatever
}
// Now do everything with the number directly instead of the string
Jon Skeet
+1  A: 

Use TryParse.

string value = "123";
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
    ...
Gerrie Schenck
+2  A: 

If the value is meant to be an integer, and that is what it should be naturally used for then I'd parse it to an int - i.e. use the type that's most appropriate for the meaning of the data.

For example, often dropdown lists are populated from a database lookup table anyway - if that stores the item key as an integer then I think you should consistently handle it as one. Likewise, if the key of selected item is being stored in the db again then it needs to be converted to an int at some point anyway.

AdaTheDev