Search code examples
c#tostring

Is it good practice to use ToString() to convert a number directly to a string?


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();

Solution

  • 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