Skip to content

Instantly share code, notes, and snippets.

@mstum
Created June 7, 2017 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstum/4b59cc5acdf15b50cb42f0afcbf7ab9a to your computer and use it in GitHub Desktop.
Save mstum/4b59cc5acdf15b50cb42f0afcbf7ab9a to your computer and use it in GitHub Desktop.
T4 Template to implement the Builder Pattern
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
var nsName = "Testing";
var className = "MyTestClass";
var accessor = "public";
var classCtorAccessor = "public";
// Property Name => Type
var properties = new List<Tuple<string, string>>
{
Tuple.Create("RequestId", "string"),
Tuple.Create("Foo", "int")
};
Func<string, string> PropToArg = (prop) => prop.Substring(0,1).ToLower() + prop.Substring(1);
var ctorList = string.Join(", ", properties.Select(kvp => kvp.Item2 + " " + PropToArg(kvp.Item1)));
#>
namespace <#= nsName #>
{
<#= accessor #> partial class <#= className #>
{
partial void ValidateArgument(string argName, object value);
<# foreach(var prop in properties) { #>
<#= accessor #> <#= prop.Item2 #> <#= prop.Item1 #> { get; }
<# } #>
<#= classCtorAccessor #> <#= className #>(<#= ctorList #>)
{
<# foreach(var prop in properties) { #>
ValidateArgument(nameof(<#= PropToArg(prop.Item1) #>), <#= PropToArg(prop.Item1) #>);
<#= prop.Item1 #> = <#= PropToArg(prop.Item1) #>;
<# } #>
}
}
<#= accessor #> partial class <#=className#>Builder
{
<# foreach(var prop in properties) { #>
<#= accessor #> <#= prop.Item2 #> <#= prop.Item1 #> { get; set; }
<# } #>
<#= accessor #> <#= className #> Build<#= className #>()
{
var result = new <#= className #>(<#= string.Join(", ", properties.Select(p => p.Item1)) #>);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment