Skip to content

Instantly share code, notes, and snippets.

@couchand
Created June 19, 2015 19:40
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 couchand/30bad0c6973746d458a8 to your computer and use it in GitHub Desktop.
Save couchand/30bad0c6973746d458a8 to your computer and use it in GitHub Desktop.
Generate an immutable data structure with a T4 template
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#
var name = "Badge";
var fields = new Dictionary<string, string>{
{ "UserId", "string" },
{ "BadgeId", "int?" },
{ "StartDate", "DateTime" },
{ "EndDate", "DateTime" }
};
var isFirst = true;
#>
using System;
namespace Stuff
{
class <#= name #>
{
<# foreach (var pair in fields) { #>
public <#= pair.Value #> <#= pair.Key #> { get; }
<# } #>
public <#= name #> (<# foreach (var pair in fields) { #><#= isFirst ? "" : ", "#><# isFirst = false; #><#= pair.Value #> <#= pair.Key #><# } #>)
{
<# foreach (var pair in fields) { #>
this.<#= pair.Key #> = <#= pair.Key #>;
<# } #>
}
<# foreach (var pair in fields) {
isFirst = true;
#>
public <#= name #> With<#= pair.Key #>(<#= pair.Value #> new<#= pair.Key #>)
{
return new <#= name #> (<# foreach (var p in fields) { #><#= isFirst ? "" : ", "#><# isFirst = false; #><#= p.Key == pair.Key ? "new" : "" #><#= p.Key #><# } #>);
}
<# } #>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment