626

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

0

13 Answers 13

897
string myString = myInt.ToString(); 
Sign up to request clarification or add additional context in comments.

12 Comments

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.
@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.
@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.
@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.
The comments on this answer are ridiculous.
|
576
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

also you can do this string count = "" + intCount;
Are all these solutions equally efficient? I'd imagine i.ToString() does some unnecessary boxing of the int, but perhaps that is optimised anyway.
.ToString() is the most efficient way to do the conversion. All of the other methods presented here will eventually call .ToString() anyway.
36

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

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

Comments

16

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

int var1 = 2; string var2 = var1.ToString(); 

Comments

12

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

12
string str = intVar.ToString(); 

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

string str = "hi " + intVar; 

Comments

10

or:

string s = Convert.ToString(num); 

Comments

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

4 Comments

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!
@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, 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.
What is the advantage of this way to do it? It uses obscure classes and just makes it complicated for no benefit
@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.
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...

Comments

1
string s = "" + 2; 

and you can do nice things like:

string s = 2 + 2 + "you" 

The result will be:

"4 you"

Comments

0

if you're getting from a dataset

string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString(); 

2 Comments

You could even leave out that Convert.ToInt32 call
@HansKesting aha I didn't see that. it'll do.
0

Using template literals in C# is the easiest way to do it.

int userId = 9; printUserIdToConsole($"{userId}"); // equivalent to userId.ToString() but cleaner public void printUserIdToConsole(string userId) { Console.WriteLine(userId); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.