How can I convert an int datatype into a string datatype in C#?
13 Answers
string myString = myInt.ToString(); 12 Comments
int from the question would not be null. But for the sake of argument, data type int? could be null, but that would return an empty string, not throw. However, should the data type not be int, but instead be an int? boxed to object, then yes, it would throw if null.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(); 3 Comments
string count = "" + intCount;.ToString() is the most efficient way to do the conversion. All of the other methods presented here will eventually call .ToString() anyway.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("}"); } Comments
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 Comments
using System.ComponentModel; TypeConverter converter = TypeDescriptor.GetConverter(typeof(int)); string s = (string)converter.ConvertTo(i, typeof(string)); 4 Comments
i.ToString -- the rest are only here for the sake of completeness and fun.typeof(int) and typeof(string) you could have Type variables and it would find and use an appropriate converter whenever one exists.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...
Comments
if you're getting from a dataset
string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();