Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BestPractice for conditions with strings and numbers

Tags:

string

c#

integer

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)
like image 508
Rookian Avatar asked Feb 10 '10 09:02

Rookian


1 Answers

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
like image 96
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet