views:

457

answers:

6

I have an array like this:

object[] args

and need to insert those args in a string, for example:

str = String.Format("Her name is {0} and she's {1} years old", args);

instead of:

str = String.Format("Her name is {0} and she's {1} years old", args[0], args[1]);

NOTE: Actually the first line of code worked! But args[1] was missing! Sorry and thank you. Points for every one :)

+17  A: 

Your first example should work fine, provided there are at least two objects in the array args.

object[] args = new object[] { "Alice", 2 };
str = String.Format("Her name is {0} and she's {1} years old", args);
csharptest.net
+3  A: 

It should work just the way you want it to. The String class has the following Format method definition:

public static string Format(string format, params object[] args);

Seeing as how the "args" in your example is an array of objects, it should fit right in.

Skinniest Man
+1  A: 

Your second code-block would do what I think you are trying to accomplish.

string.Format("Hello {0}, {1} and {2}", new object[] { "World", "Foo", "Bar" });
sshow
+1  A: 

Did you even try the first line? Did you see that it should work the same as the second?

leppie
+3  A: 

I'm not sure what you're asking, but either of those should work, considering that one of the signatures for the String.Format() function is

Public Shared Function Format(ByVal format As String, ByVal ParamArray args() As Object) As String

More junk I copied from Visual Studio:

Summary: Replaces the format item in a specified System.String with the text equivalent of the value of a corresponding System.Object instance in a specified array.

Parameters: format: A composite format string. args: An System.Object array containing zero or more objects to format.

Return Values: A copy of format in which the format items have been replaced by the System.String equivalent of the corresponding instances of System.Object in args.

Exceptions: System.ArgumentNullException: format or args is null. System.FormatException: format is invalid. -or- The number indicating an argument to format is less than zero, or greater than or equal to the length of the args array.

-- Oops on the VB, but you get the point.

Cory Larson
I love that the API definition you gave was for VB. ;-)
Dan Esparza
+2  A: 

Both your examples do the same thing - String.Format has an overload which accepts an object[] instead of specifying each argument separately.

Lee