Basically, he’s proposing an ‘aggregated’ or‘lifted’ version of ToString() that would render this:
string foo = p.ToString("My name is {FirstName} {LastName} and my birthdayis {Birthdate:MM/dd/yyyy}");
Semanticallyequivalent to this:
string foo =String.Format("My name is {0} {1} and my birthday is{2:MM/dd/yyyy}",p.FirstName,p.LastName,p.BirthDate);
It’sdefinitely syntactic sugar, but I’ve got a notorious sweet tooth and Ilike it. However, I don’t think I’d do this in a class library fora couple of reasons:
· Performance.
· Lackof type safety.The format string in Scott’s suggestion is coupled to the type of target object.If Person doesn’t expose a field/property called FirstName, the only wayyou’ll find out about it is via an exception at runtime. Furthermore,because the member names are embedded inside of opaque strings, tools likeCodeSmith and Resharper can’t include them in a Rename refactoring. Thiscould impeded productivity on large projects that make heavy use of this idiom.
I do think it’spretty cool, though. My original thought was this could be a pretty coollanguage feature, implemented by compile-time code generation much the wayanonymous delegates are created in C# 2.0. Thinking more about it, though, I’mnot sure how you would disentangle the member references from the formattingstring so as to make them visible to the compiler without reducing back tosomething nearly identical to the existing String.Format().
Language design is hard.
