Domanda

I'm writing an extension for string.Format (which I've done before with no problems.)

My extension:

    public static string FormatWith(this string source, params object[] args) {
        source.ThrowIfNull("source");

        return string.Format(source, args);
    }

My test:

    [TestMethod]
    public void FormatWith_ShouldReturnCorrectResult_FromValidArgs() {
        var expected = "testing 123";
        var actual = "test".FormatWith("ing", " ", 123);

        Assert.AreEqual(expected, actual);
    }

In my test, after the call to FormatWith, actual should be "testing 123" but it is just "test".

My test's message:

    Assert.AreEqual failed. Expected:<testing123>. Actual:<test>.

I've tried passing types other than string into the extension but the result is unchanged. And I'm sure source.ThrowIfNull is not throwing an exception.

So what gives? Am I overlooking something? A nice answer would show me a working implementation of FormatWith along with an explanation of why my implementation is not working.

Edit: I'm an idiot and completely forgot about {0}, {1}... I use this on a daily basis too. Will accept first answer when timer is up. Thanks guys.

È stato utile?

Soluzione

I'm not a .NET guy, but I can read API docs: http://www.dotnetperls.com/string-format

If I'm not mistaken, your source string needs to explicitly add your arguments to the string.

var actual = "test{0}{1}{2}".FormatWith("ing", " ", 123);

Feel free to correct me .NET folks.

Altri suggerimenti

You are looking for String.Concat. String.Format doesn't work like that.Only if you specify arguments like this:

string.Format("{0}, {1} ....",source,args);

Which you can not because you don't know the number of arguments.So you can use String.Concat or String.Join instead.

Rather than modify your usage of the function as some other others suggested, here's an implementation of FormatWith that will work as you intended it:

public static string FormatWith(this string source, params object[] args)
{
    var arguments = new List<object> {source};
    arguments.AddRange(args);

    return String.Concat(arguments);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top