FormattableString
has been Introduced in C# 6.0. As we can use same string formatting using string
object why is there need of using FormattableS
As an aside, https://www.meziantou.net/interpolated-strings-advanced-usages.htm covers some examples of what FormattableString allows you to do (e.g. auto-parameterising SQL statements)
e.g.
void ExecuteNonQuery(DbConnection connection, FormattableString formattableString)
{
using (var command = connection.CreateCommand())
{
// Replace values by @p0, @p1, @p2, ....
var args = Enumerable.Range(0, formattableString.ArgumentCount).Select(i => (object)("@p" + i)).ToArray();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = string.Format(formattableString.Format, args);
// Create parameters
for (var i = 0; i < formattableString.ArgumentCount; i++)
{
var arg = formattableString.GetArgument(i);
var p = command.CreateParameter();
p.ParameterName = "@p" + i;
p.Value = arg;
command.Parameters.Add(p);
}
// Execute the command
command.ExecuteNonQuery();
}
}
using (var sqlConnection = new SqlConnection())
{
sqlConnection.Open();
ExecuteNonQuery(sqlConnection, $@"UPDATE Customers SET Name = {"Meziantou"} WHERE Id = {1}");
}