How to imitate string.Format() in my own method?
You need to copy the method signature from string.format.
public void WriteLine(string text,params object[] args) { this.StringList.Add(string.Format(text,args));}
As suggested by ChaosPandion you can also include overloads to prevent array creation
public void WriteLine(string text) { this.StringList.Add(text);}public void WriteLine(string text,object arg0) { this.StringList.Add(string.Format(text, arg0));}public void WriteLine(string text,object arg0, object arg1) { this.StringList.Add(string.Format(text, arg0, arg1));}public void WriteLine(string text,object arg0, object arg1, object arg2) { this.StringList.Add(string.Format(text, arg0, arg1, arg2));}
I wouldn't go past arg2 as string.format doesn't so the benefit disappears.
There is one edge case you might want to take pains to avoid. The following code will write the string {0} to the console
Console.WriteLine("{0}");
However, you use one of the implementations of WriteLine suggested by others in this answer, those implementations will throw an exception:
WriteLine("{0}"); //throws exception
The easiest fix is either to have two overloads of WriteLine or to modify the suggested code slightly to handle the edge case:
public void WriteLine(string text,params object[] args) { var message=args.Length==0 ? text : string.Format(text, args); this.StringList.Add(message);}