Created
June 19, 2015 19:40
-
-
Save couchand/30bad0c6973746d458a8 to your computer and use it in GitHub Desktop.
Generate an immutable data structure with a T4 template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<#@ 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