Passing extra argument to string.Format() function in C#
Asked Answered
S

2

7

Is there any side effect of passing and extra argument to the string.Format function in C#? I was looking at the string.Format documentation at MSDN but was unable to find an answer.

E.g.:

string str = string.Format("Hello_{0}", 255, 555);

Now, as you can see in the according to format string, we are supposed to pass only one argument after it, but I have passed two.

I have tried it on my end and everything looks fine to me, but I just want to make sure that it will not cause any problems in later runs.

Stew answered 30/11, 2012 at 12:51 Comment(3)
What do you mean by "side effect" and "extra argument"? An example would help us understand your question.Lyophilic
I'd say it depends on how it was implemented - if the implementation goes through the params one at a time, than the longer the list, the longer it will take, regardless of how many formatting options it actually has in the format string.Piscator
@Oded: Yes, I tried it, and everything looks fine to me. Since I am new to C# and from C background, I just want to make sure.Stew
O
8

Looking in Reflector, it will allocate a little more memory for building the string, but there's no massive repercussion for passing in an extra object.

There's also the "side effect" that, if you accidentally included a {n} in your format string where n was too large, and then added some spare arguments, you'd no longer get an exception but get a string with unexpected items in.

Outmarch answered 30/11, 2012 at 12:54 Comment(0)
T
3

If you look at the exception section of the link you provide for string.Format

"The index of a format item is less than zero, or greater than or equal to the length of the args array."

Microsoft doesn't indicate that it can throw if you have too much arguments, so it won't. The effect is a small loss of memory due to an useless parameter

Tagliatelle answered 30/11, 2012 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.