[c#] Convert int to string?

How can I convert an int datatype into a string datatype in C#?

This question is related to c# string int

The answer is


Just in case you want the binary representation and you're still drunk from last night's party:

private static string ByteToString(int value)
{
    StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
    BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
    foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
    {
        builder.Append(bit ? '1' : '0');
    }
    return builder.ToString();
}

Note: Something about not handling endianness very nicely...


If you don't mind sacrificing a bit of memory for speed, you can use below to generate an array with pre-calculated string values:

static void OutputIntegerStringRepresentations()
{
    Console.WriteLine("private static string[] integerAsDecimal = new [] {");
    for (int i = int.MinValue; i < int.MaxValue; i++)
    {
        Console.WriteLine("\t\"{0}\",", i);
    }
    Console.WriteLine("\t\"{0}\"", int.MaxValue);
    Console.WriteLine("}");
}

using System.ComponentModel;

TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));

Further on to @Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.

It seems pretty much a tie between:

int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time

The ToString method of any object is supposed to return a string representation of that object.

int var1 = 2;

string var2 = var1.ToString();

string s = "" + 2;

and you can do nice things like:

string s = 2 + 2 + "you" 

The result will be:

"4 you"


string str = intVar.ToString();

In some conditions, you do not have to use ToString()

string str = "hi " + intVar;

or:

string s = Convert.ToString(num);

string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();

int num = 10;
string str = Convert.ToString(num);

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...