Yair Ashen
Yair Ashen

Reputation: 29

What is the difference between these methods of converting an int to a string?

string s = i.ToString();

string s = Convert.ToString(i);

string s = string.Format("{0}", i);

string s = string.Empty + i;

string s = new StringBuilder().Append(i).ToString();

Upvotes: 2

Views: 97

Answers (1)

Matthew Haugen
Matthew Haugen

Reputation: 13286

They're just several ways of doing ultimately the same thing, the idea being that they allow you ease in whichever context you need them. They're all functionally equivalent, in your current usage. Of course, in other uses, they could be used to achieve radically different results.

string s = i.ToString();

This one is necessary because it must override object.ToString(), so this becomes the base for all the rest.

string s = Convert.ToString(i);

This one just calls int.ToString(), and they probably provide it just so that Convert.ToString(object) doesn't have to deal with boxing and unboxing of the int value.

string s = string.Format("{0}", i);

This one is a bit different, but still relies on int.ToString(). In its current form, it wouldn't be particularly useful and would be particularly inefficient, but basically string.Format is a quick way to format strings (obviously), and uses object.ToString() (or IFormattable.ToString() when available and useful, as it is for int when a formatter is present).

string s = string.Empty + i;

Again, not particularly useful in its current position, but this supports more advanced operations. string s = "This is the number: " + i; is a lot easier than having to call the ToString explicitly, so this is just a language feature--syntactic sugar, as it were.

string s = new StringBuilder().Append(i).ToString();

This one is like string.Format. As it stands, this is an inefficient thing to do. But if you were actually building something with a StringBuilder, it would be nice not to have to box and unbox your int.


It's kind of like this, what's the difference between these two?

string[] nums = new [] { "1", "2", "3", "4" };

for (int v = 0; v < nums.Length; v++)
    Console.WriteLine(nums[v]);

and

string[] nums = ...;

foreach (var v in nums)
    Console.WriteLine(v);

They're just two ways of doing essentially the same thing.

Upvotes: 3

Related Questions