views:

114

answers:

4

I just noticed that I can do the following, which came as a complete surprise to me:

Console.WriteLine("{0}:{1}:{2}", "foo", "bar", "baz");

This works for the Write method too. What other methods have signatures supporting this, without requiring the use of String.Format?

Debug.WriteLine doesn't...
HttpResponse.WriteLine doesn't...

(And on a side note, I could not find a quick way of searching for this with Reflector. What is a good way to search for specific signatures?)

Edit:

Specifically for the 3.5 framework.

+4  A: 

StringBuilder instances have an AppendFormat method.

StringWriter instances have a Write overload which takes format parameters.

benjynito
Interesting how they used a separate method name for this, I assume because otherwise it would collide with the `(String, Int32, Int32)` signature. Makes me wonder why they did not standardize on this approach for consistency, and make a `Debug.WriteLineFormat` method instead.
RedFilter
A: 

The StringBuilder class has a method called AppendFormat which behaves in the same way

Nick Allen - Tungle139
+4  A: 

There are a lot of methods that support this throughout the framework. All subclasses of TextWriter (and therefore StreamWriter and StringWriter and their subclasses) will inherit the Write method that supports this.

Another example that is often used is StringBuilder.AppendFormat.

You can write your own methods to support this too. You can do it by having an overload with a format string parameter and another parameter with the params keyword, like this:

public void Foo(string message) {
    // whatever
}

public void Foo(string format, params string[] arg) {
    Foo(string.Format(format, arg));
}
Mark Byers
*There are a lot of methods* - such as? That **is** the question :)
RedFilter
@Orbman: Sorry! That's true, but others have already suggested about 4 more good answers and I don't want to just plagarize everyone else's answers into my post. Instead I tried to come up with some new and related information that might be useful to you or someone else here. :)
Mark Byers
@Mark - absolutely! All contributions gladly accepted :)
RedFilter
@Orbman: If you put 'TextWriter' into Reflector you get a lot of matches, most of which probably support this.
Mark Byers
+1: good info, thanks!
RedFilter
+1  A: 

Debug.WriteLine(string, params Object[] args) overload does this as well, being added in .Net 4.0.

Nick Craver
That seems to be supported in .NET Framework 4 only. Does not work in 3.5.
RedFilter
@OrbMan - Good catch, added that to the description.
Nick Craver