0

Is it good practice to convert a number to a string directly using ToString()? Like this:

string numStr = 0.ToString();

Or should the number be entered into an int variable first and then use ToString() on that? Like this:

int num = 0;
string numStr = num.ToString();
Dov Miller
  • 1,958
  • 5
  • 34
  • 46
  • 15
    Can't you just enter `"0"`, instead of casting int to string? – Bukk94 Feb 27 '20 at 10:57
  • 4
    Side note: `0.ToString();` as well as `num.ToString()` is *culture specific* (it uses `CultureInfo.CurrentCulture`), in some (very special for just `0`) cases you can have *unexpected* results – Dmitry Bychenko Feb 27 '20 at 10:57
  • If you are using int num = 0; string numStr = num.ToString(); then use Convert.ToString(num) – Zeeshan Feb 27 '20 at 11:03
  • 1
    @Shocky That's almost always OK for `0`, but for a floating point number then `0.1.ToString()` != `"0.1"` for, say, the German locale. So you have to be careful just putting string representations of numbers into code rather than using `ToString()` (or equivalent). – Matthew Watson Feb 27 '20 at 11:03
  • The IL versions of both fragments are basically identical – Hans Kesting Feb 27 '20 at 11:13

2 Answers2

1

Its a Good practice to store your numbers in a Variable and then using the ToString() See example at the end

ToString() accepts an over load like ToString(IFormatProvider provider) where you can specify culture-specific format information

Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));

The Alternative to ToString() is to use Convert.ToString(Int value) the difference is that Convert also handles null values

var str = Convert.ToString(value);
var str1 = Convert.ToString(value,CultureInfo.InvariantCulture);

Is it good practice to convert a number to a string directly using ToString()? Like this:

Example

1.ToString(); // Compiles fine
-1.ToString(); // Compile error, note you can surround it with parenthesis to get it to compile
Clint
  • 6,011
  • 1
  • 21
  • 28
0

when you say "string a = 0.ToString();"
----------------------^-----here you are already declaring that its a string so saying .ToString(); is redundant