开发者

BestPractice for conditions with strings and numbers

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 ZeroNumb开发者_JS百科er = "0";
if (SelectedItem.Value == _zeroNumber) ...

or

if (Int.Parse(SelectedItem.Value) == 0)


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


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.


Use TryParse.

string value = "123";
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
    ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜