InterpolatedStrings 2.0.0-beta1

This is a prerelease version of InterpolatedStrings.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package InterpolatedStrings --version 2.0.0-beta1                
NuGet\Install-Package InterpolatedStrings -Version 2.0.0-beta1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="InterpolatedStrings" Version="2.0.0-beta1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add InterpolatedStrings --version 2.0.0-beta1                
#r "nuget: InterpolatedStrings, 2.0.0-beta1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install InterpolatedStrings as a Cake Addin
#addin nuget:?package=InterpolatedStrings&version=2.0.0-beta1&prerelease

// Install InterpolatedStrings as a Cake Tool
#tool nuget:?package=InterpolatedStrings&version=2.0.0-beta1&prerelease                

InterpolatedStrings

InterpolatedStringBuilder is like a StringBuilder but for Interpolated Strings (FormattableString)

It's an implementation of FormattableString with support for concatenating strings, replace, insert, etc.

Quickstart

  1. Install the NuGet package InterpolatedStrings or NuGet package InterpolatedStrings.StrongName
  2. Add using InterpolatedStrings; to your usings.
  3. See examples below.

Basics

How to create an InterpolatedStringBuilder, append some more interpolated strings

string arg1 = "FormattableString";
var s = new InterpolatedStringBuilder($"This is exactly like {arg1}");

// s.Format now is equal to "This is exactly like {0}"
// s.Arguments contain [arg1]

string arg2 = "additional";

// += is an operator overload, but you can also call s.Append(...);
s += $"... but you can append {arg2} FormattableString instances";

// s.Format now is equal to "This is exactly like {0}... but you can append {1} FormattableString instances"
// s.Arguments now contains [arg1, arg2]

Sample Usage: Dynamic SQL building

int categoryId = 1;
double maxPrice = 20.50;

//------------------------------------------------------------------------------
// Creates an initial SQL query, and appends more conditions.
// Embedded objects are NOT converted to strings: they are still kept 
// as objects (in Arguments list), and the underlying format string just keeps
// the numbered placeholders
//------------------------------------------------------------------------------
var query = new InterpolatedStringBuilder($"SELECT * FROM Products");
query += $" WHERE CategoryId={categoryId}";
query += $" AND price<={maxPrice}";

// query.Format now is "SELECT * FROM Products WHERE CategoryId={0} AND price<={1}"
// query.Arguments now is [categoryId, maxPrice]

//------------------------------------------------------------------------------
// Then you can create your own methods (or extensions) to convert back from
// InterpolatedStringBuilder into a valid SQL statement
//------------------------------------------------------------------------------
string sql = string.Format(query.Format, query.Arguments.Select((arg, i) => "@p" + i.ToString()).ToArray());
Assert.AreEqual("SELECT * FROM Products WHERE CategoryId=@p0 AND price<=@p1", sql);

// If you were using Dapper you could pass parameters like this:
// var sqlParms = new DynamicParameters();
// for (int i = 0; i < query.Arguments.Count; i++) { dbArgs.Add("p" + i.ToString(), query.Arguments[i].Argument); }
// var products = connection.Query<Product>(sql, sqlParms)

Conditional Appends

int? categoryId = null;
double? maxPrice = 20.50;

//------------------------------------------------------------------------------
// Fluent API allows short syntax for appending multiple blocks,
// and using conditions
//------------------------------------------------------------------------------
var query = 
    new InterpolatedStringBuilder($"SELECT * FROM Products WHERE 1=1")
    .AppendIf(categoryId != null, $" AND CategoryId={categoryId}")
    .AppendIf(maxPrice != null, $" AND price<={maxPrice}")
    ;

// Now query.Format is "SELECT * FROM Products WHERE 1=1 AND price<={0}"

Multiline Blocks, Replaces, Inserts, etc.

Using Raw String Literals:

int? categoryId = 3;
double? maxPrice = null;

//------------------------------------------------------------------------------
// Raw String Literals allows us to easily write multiline blocks
//------------------------------------------------------------------------------
var query = new InterpolatedStringBuilder($$"""
    SELECT * FROM Products
    /***where***/
    ORDER BY Category, Name
    """);

var wheres = new InterpolatedStringBuilder();
wheres.AppendIf(categoryId != null, $" AND CategoryId={categoryId}");
wheres.AppendIf(maxPrice != null, $" AND price<={maxPrice}");

if (wheres.Format.Length> 0)
{
    wheres.Remove(0, " AND ".Length).Insert(0, $"WHERE ");
    query.Replace("/***where***/", wheres);
}

Assert.AreEqual("""
    SELECT * FROM Products
    WHERE CategoryId={0}
    ORDER BY Category, Name
    """, 
    query.Format);

See more examples in unit tests.

How to Collaborate?

Please submit a pull-request or if you want to make a sugestion you can create an issue or contact me.

Stargazers over time

Star History Chart

License

MIT License

See full documentation here

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.0-beta2 96 6/28/2023
2.0.0-beta1 85 6/25/2023