I have T4 template where I'd like to generate an .cs file.
I have an array of System.Data.DataColumn
that i'd like to use as a private variables in my generated code file.
I'm using ColumnName
as variable name, Value
as variable value and DataType
as variable data type.
I'm thinking on how do I initialize defined variables in this case:
ColumnName = "col1"
ColumnValue = "text"
DatType = System.String
I'd like to see output: private System.String col1 = "text";
Variable definition in T4 template:
private <#= DataType.ToString() #> <#= ColumnName #> = "<=# ColumnValue #>"
I'm thinking about writing helper method, that will return variable initialization string for common data types. Something like:
public string ValueInitializerString
{
get
{
string valueString;
if (this.DataType == typeof(int))
{
valueString = this.Value.ToString();
}
else if (this.DataType == typeof(string))
{
valueString = string.Format("\"{0}\"", this.Value);
}
else if (this.DataType == typeof(DateTime))
{
DateTime dateTime = (DateTime)this.Value;
valueString = string.Format("new DateTime({0}, {1}, {2}, {3}, {4}, {5}, {6})",
dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond);
}
else
{
throw new Exception(string.Format("Data type {0} not supported. ", this.DataType));
}
return valueString;
}
}
If someone did something similar, could you advice if this is a good idea or it could be done in more convenient way? Maybe I should read something?