• Feeds

    Subscribe in a reader

  • Ads

Lifted access to .ToString()

Scott lays out an interesting littleidiom over here.

Basically, he’s proposing an ‘aggregated’ or‘lifted’ version of ToString() that would render this:

Person p = newPerson("Scott","Hanselman",new DateTime(1974,1,22);
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. Really the only way toimplement this would be via Reflection, and reflection is slow relative tonative member access. I expect a library implementation of Scott’s idiomto be aboutan order of magnitude slower than native member access. That amounts toexpensive sugar.

·        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.

 

#1 Ayende Rahien on 1.28.2005 at 1:31 AM

Boo (http://boo.codehaus.org) can do it now.The syntax is something like:"Sometihng ${name} ${surname} ${etc}"This cause compile time analasis and checking, and should greatly reduce the risk of both your points.

#2 John Brett on 5.09.2005 at 12:38 AM

I have implemented pretty much exactly this solution for a project I'm working on in-house.We wanted the descriptive text for the objects to be configurable, so this design fitted very well.Since the primary role of the function was to supply tooltips to UI elements, I wasn't overly fussed about performance, and the flexibility it offers has been a real help.