Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@binki
Last active January 18, 2017 18:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binki/dbeee64273b404042e3ae81f042358be to your computer and use it in GitHub Desktop.
Save binki/dbeee64273b404042e3ae81f042358be to your computer and use it in GitHub Desktop.
Play with C# string interpolation
SELECT * FROM blah b WHERE b.Thing = @p0
p0=plant
SELECT * FROM anotherThing at WHERE at.Value = 'asdf'
using System;
namespace FormattablePlay
{
class Program
{
static void Main(string[] args)
{
var stringVar = "plant";
Append($"SELECT * FROM blah b WHERE b.Thing = {stringVar}");
var rawSql = new RawSql("'asdf'");
Append($"SELECT * FROM anotherThing at WHERE at.Value = {rawSql}");
}
static void Append(IFormattable query)
{
var formatter = new SqlFormatInfo();
Console.WriteLine(query.ToString(null, formatter));
foreach (var p in formatter.Parameters)
Console.WriteLine($"\t{p.Key}={p.Value}");
Console.WriteLine();
}
}
}
namespace FormattablePlay
{
class RawSql
: ISqlFormattable
{
string Sql { get; }
public RawSql(
string sql)
{
Sql = sql;
}
public string ToSql() => Sql;
public override string ToString() => Sql;
}
internal interface ISqlFormattable
{
string ToSql();
}
}
using System;
using System.Collections.Generic;
namespace FormattablePlay
{
class SqlFormatInfo
: ICustomFormatter
, IFormatProvider
{
Dictionary<string, object> parameters { get; } = new Dictionary<string, object>();
public IReadOnlyDictionary<string, object> Parameters => parameters;
int LastParameterIndex { get; set; }
public string Format(string format, object arg, IFormatProvider formatProvider)
{
var sqlFormattable = arg as ISqlFormattable;
if (sqlFormattable != null)
return sqlFormattable.ToSql();
var parameterName = $"p{LastParameterIndex++}";
parameters[parameterName] = arg;
return $"@{parameterName}";
}
public object GetFormat(Type formatType)
=> this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment