Using Embedded Expressions in XML to Replace String.Format And StringBuilder

If you have been using StringBuilder or String.Format to build strings, they provide nice syntax to replace placeholders such as {0}, {1} etc with the values passed in the second parameter to the method. Although I have been using this syntax to print and create customized displays, I still feel that there are sometimes harder to read because of the noise the method and placeholders add to the code. With the awareness of XML into the vb language, you can leverage embedded expression to build customized strings from XML by calling the Value property on the XML literal. Below is an example that demonstrates this usage.

image

image 

In the above example, I am creating an XML literal called display. Display XElement has embedded expressions for product name, unit price and unitsinstock. All 3 literals create one big string which I can extract by calling Value property available on the XElement. Using XElement this way makes code more readable, allows embedding expressions and also preserves white spacing and carriage returns.

Comparing this example to the string.format that I have used later down the code, you can can see that I have to deal with placeholders which later get replaced making it harder to read because part of the code is down below. Also I have to manage my own spacing and carriage returns by explicitly using Environment.NewLine.

Personally if I had been doing vb, I would prefer XML syntax to create large strings because they make code more readable and intent becomes more clear. Hopefully C# will get this support soon.

No Comments