string.Format
returns formatted string, you have to assign it back to your variable:
something = string.Format("Some_Point({0},{1}),", item.X, item.Y);
Pregunta
public override string ToString()
{
string token = "something";
foreach (something item in this)
{
something = something + "Some_Point({0},{1}),";
string.Format(something, item.X, item.Y);
}
return something+= "anything";
}
This is the overridden ToString()
method of a custom collection. The problem here is that String.Format
isn't substituting the values of X and Y. It does substitute whenever I add return before String.Format
. I am just starting to learn C# and have no idea what is causing this strange behaviour.
Solución
string.Format
returns formatted string, you have to assign it back to your variable:
something = string.Format("Some_Point({0},{1}),", item.X, item.Y);
Otros consejos
If you have lots of strings to append in a single result, you should use StringBuilder
class from System.Text
namespace. That is a good pratice because a string
object is immutable and every time you change something, a new instance is create on the heap. Try to do something like this:
using System.Text;
...
public override string ToString()
{
StringBuilder s = new StringBuilder("something initial if you need");
foreach (something item in this)
{
s.AppendFormat("Some_Point({0},{1}),", item.X, item.Y);
}
s.Append("something else");
return s.ToString();
}
If you want know more about why avoid string concatenation, look this article: http://msdn.microsoft.com/en-us/library/ms182272(v=vs.80).aspx
string.Format
returns a string, so:
something = string.Format(something, item.X, item.Y);