Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating a string stored in a database

We would like to maintain the emails that are sent from our ASP.NET Web Application in a database. The idea was that the format of emails are stored in a database.

The problem is that emails should include order specific information, e.g.:

Thank you for your order John Smith,

your order 1234 has been received

What I'm trying to achieve is that I have used string verbatims in the database column values where it would be stored like this:

Thank you for your order {o.customer},

your order {o.id} has been received

I'm curious as to whether it is possible to do string interpolation where the values are already in the string that is formatted. If I try to use String.Format(dbEmailString) it throws me exception:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

like image 705
johnnyCasual Avatar asked Jul 13 '16 15:07

johnnyCasual


People also ask

What is interpolation string?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Can I use string interpolation?

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.

Which is the correct syntax of string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.


1 Answers

String interpolation is a compile time feature. You can do what you want using the regular String.Format:

var formattedEmail = String.Format("Thank you for your order {0}, your order {1} has been received", o.customer, o.id);

If you've got a requirement to replace out various different placeholders with the values, perhaps you need to be looking for a more dynamic templating system, a very basic one could be done with String.Replace.

The bottom line is you can't reference variables in your code directly from stored strings in this fashion - you'll need to process the string in some way at runtime.

like image 50
James Thorpe Avatar answered Oct 12 '22 13:10

James Thorpe