tags:

views:

88

answers:

2

Is there any sane reason why the function String.Format in .net (for C# and VB.net at least) shared and not like .split, .substring or whatever a normal function.

What would be bad about

Dim a as String = "1+2={0}".format(1+2) (would be good)

vs.

Dim a as String = String.Format("1+2={0}",1+2) (the way it works)

It always bugs me when using this function - which i do quite often.

Thx.

+3  A: 

Its just a design decision - it could really work both ways. I think they decided to make it static/shared because of (1) historic reasons, to make it more similar to C/C++ (2) because you can argue that the format string is not a "real" text, in most cases people use some inlined constant, and it reads better if this is an argument of a function.

Grzenio
+5  A: 

Maybe Eric Lippert still has the design notes on that but apart from that I don't think this can be accurately answered.

Still, as a workaround, if you desperately need this, then you can write an extension method:

public static string Format(this string fmt, params object[] args) {
    return string.Format(fmt, args);
}

My guess is that most string methods actually operate on the string, transforming it in a straightforward and foreseeable manner, such as Substring, Replace and PadLeft. With Format the core string is just a pattern that is applied to integrate the operands into. Conceptually most instance methods on string can be seen as manipulating a string (I know, this isn't what happens, I'm just painting a picture here), while the static methods just work with it.

As noted, just a guess. In the end it probably was just a decision and the reason was lost in time.

Joey
I know - have already coded such function, only to find out that it needs at least .net3.5 - and our technological cutting-edge company is still on .net2.0
DanielAt
Extension methods only need the C# 3 *compiler*, the resulting code still runs fine with only .NET 2.
Joey
Yeah - but for asp.net its not that easy to change the compiler (afaik).
DanielAt
I don't have the design notes for the runtime library, just for the language, sorry.
Eric Lippert