Last post I showed a cool way to parse strings into typed objects. In this one, I want to show the opposite. How to build strings using a template and an object.

The idea is to use a template like {BirthDate:D} My name is {FirstName} {LastName} and I'm cool. and an object with properties BirthDate, FirstName and LastName to fill in the placeholder values and apply optional formatting. There are several uses for a utility like this but my favorite use is templated email messages.

Kudos to Scott Hanselman for this solution.

The nice part about this solution is that it won’t throw any exceptions if it can’t correctly build the string. It will just leave the bad part of the template in the result. Also, it supports Format Providers which also allows for specific culture targeting:

You can find the code in Scott’s git hub repo

PS: I know that Scott posted about this years ago but I use this so often that I felt like it deserved another blog post…

Happy coding!


A little while ago, I had to build a desktop app that received input from devices which I had no control of. Although each implementation had similar requirements, the devices connected to the app were slightly different and so were the inputs received from them. I’ve looked for other similar implementations and found that some people implemented device specific parsers. Furthermore, they used configuration to select the correct parser. I think there is at least one issue with this approach: any change to the known inputs would require the application to change as well. Maybe there is a better way…

The trick I want to demonstrate relies on named group capturing from Regular Expression and a little fiddling with reflection.

Note: this technique works great for most scenarios but if you are looking for a super high performance solution, this is not for you.

Alright! Let’s see some code.

So with above code you can, for instance, parse a string that represents Product and Price into a typed object:

I find this most useful when you don’t really have control of the input, maybe it is a device input or a legacy system that just drop you some info. Regardless, this can save a bunch of time when the input changes or a new device needs to be supported.

You can find samples at my github repo.

Happy coding!