598

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

Sam Axe
  • 33,313
  • 9
  • 55
  • 89
The Worst Shady
  • 6,438
  • 5
  • 19
  • 15

12 Answers12

862
string myString = myInt.ToString();
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • 5
    My problem with this is that you lose type safety. myInt could be anything. Nothing here says take an integer and convert it to a string. myInt could be an object and an object can't be converted to a string. That's known at compile time, but it wouldn't even raise a runtime exception it would just allow bad data. – Timothy Gonzalez Dec 15 '16 at 16:29
  • 5
    @TimothyGonzalez That's an edge case, if you call .ToString() its usually because you need it to be a string and it can be a string. – EpicKip Feb 15 '17 at 13:58
  • @EpicKip It's a valid edgecase. – Nick Gallimore Jun 21 '18 at 14:47
  • 53
    @nfgallimore It is not a valid edge case it is not even an edge case in this situation. The OP stated he had an int type he wanted converted to a string. If it is an int type, then plain and simple the value is an int. The compiler will insure that is the case. Not even sure how you went off on that tangent. The OP didn't ask how to make sure a random reference was an integer and then convert it to a string. Perhaps in that case you have a point, but that is not the case. – AaronM Jun 22 '18 at 23:46
  • 1
    This solution throw exception for `null` values. – Mehdi Dehghani Nov 30 '18 at 16:12
  • 2
    @MehdiDehghani, data type `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. – Anthony Pegram Nov 30 '18 at 21:37
  • 1
    intValue.ToString() is good enough for 99.34% of cases. If one of the rare edge cases is possible, then code for it. If it's the result of a method call, which explicitly sets it (and you know that the user cannot manipulate it), then it is perfectly fine to use. – Jon Dec 20 '18 at 21:02
  • 41
    The comments on this answer are ridiculous. –  Mar 22 '19 at 15:16
  • 1
    By the way, you can set [format](https://stackoverflow.com/a/2947687/7786739) if you need. – 劉鎮瑲 Dec 27 '19 at 07:37
  • Just in case anyone ran into the same issue I did, make sure you mind the capital `T` in `ToString()`. – zcoop98 Oct 13 '20 at 23:56
  • 1
    can not believe to my eyes, this kind of an answer gets 800 upvote... –  Oct 28 '21 at 07:41
  • LeetCode.com says this creates an index out of range exception. It looks so simple !! – micahhoover Feb 04 '22 at 01:46
564
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();
RhinoDevel
  • 712
  • 1
  • 12
  • 25
Xavier Poinas
  • 19,377
  • 14
  • 63
  • 95
  • 6
    also you can do this `string count = "" + intCount;` – Dion Dirza Jun 10 '13 at 04:47
  • 2
    Are all these solutions equally efficient? I'd imagine i.ToString() does some unnecessary boxing of the int, but perhaps that is optimised anyway. – Stephen Holt Sep 23 '13 at 16:22
  • 54
    `.ToString()` is the most efficient way to do the conversion. All of the other methods presented here will eventually call `.ToString()` anyway. – Xavier Poinas Sep 24 '13 at 07:47
35

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("}");
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Onots
  • 2,118
  • 21
  • 28
29
int num = 10;
string str = Convert.ToString(num);
Polaris
  • 3,643
  • 10
  • 50
  • 61
15

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

int var1 = 2;

string var2 = var1.ToString();
VoodooChild
  • 9,776
  • 8
  • 66
  • 99
11
string str = intVar.ToString();

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

string str = "hi " + intVar;
Pang
  • 9,564
  • 146
  • 81
  • 122
Mehmet Ince
  • 4,059
  • 12
  • 45
  • 65
11

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
9

or:

string s = Convert.ToString(num);
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
4
using System.ComponentModel;

TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));
nmclean
  • 7,564
  • 2
  • 28
  • 37
  • This answer turned up in the low quality review queue, presumably because you didn't explain the code. If you do explain it (in your answer), you are far more likely to get more upvotes—and the questioner actually learns something! – The Guy with The Hat Sep 10 '14 at 15:00
  • 5
    @TheGuywithTheHat You'll notice that none of the answers here have any explanation of the code, particularly all the code samples in [this highly-upvoted answer](http://stackoverflow.com/a/3081940/933416), because it's obvious what they all must be doing: converting an int to a string. Truthfully we don't need anything beyond the accepted answer -- `i.ToString` -- the rest are only here for the sake of completeness and fun. – nmclean Sep 10 '14 at 17:04
  • What is the advantage of this way to do it? It uses obscure classes and just makes it complicated for no benefit – reggaeguitar May 22 '19 at 21:17
  • 2
    @reggaeguitar It's mostly a joke answer, we were purposely adding more and more obscure ways of doing one of the most basic tasks. But to your question, the advantage of this method would be if you didn't know the types in advance - instead of `typeof(int)` and `typeof(string)` you could have Type variables and it would find and use an appropriate converter whenever one exists. – nmclean May 23 '19 at 11:56
4

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...

Wolf
  • 9,679
  • 7
  • 62
  • 108
1
string s = "" + 2;

and you can do nice things like:

string s = 2 + 2 + "you" 

The result will be:

"4 you"

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Gilad F
  • 121
  • 1
  • 6
0

if you're getting from a dataset

string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();
Aruna Prabhath
  • 206
  • 2
  • 10