T4 can be used for this. This is the best variant? It depends on your scenario (suppose you published a simplified version of your real scenario).
In any case, you can define a template that generates several options. Using partial classes and methods, you can inject specific behavior into the generated code (for example, validation).
Here you can find the full source code: https://github.com/mrange/CodeStack/tree/master/q18861246/TestProject
I am using VS2013, but this works fine in VS2008 +.
I define a T4 template:
<
Itβs good practice to write supported metaprograms (my preferred term) to separate the Model, that is, what we would like to create from the view, that is, how the model is converted to code.
In this case, the model is very simple:
// The model defines *what* we like generated var model = new [] { "ValidPercent" , "Percent" , };
The view basically just iterates over the model generating the code. T4 is mostly similar to ASP / PHP.
<
To inject validation behavior, I injected an extension point into the generated code:
Partial methods basically work as events, but they are included at compile time. Partial_ValidateValue is called before m_value is assigned, ensuring that any class invariants are supported.
To implement the validation behavior, I define another part of the ValidPercent class in a separate file:
partial struct ValidPercent { public static implicit operator Percent(ValidPercent vp) { return new Percent (vp.Value); } static partial void Partial_ValidateValue(decimal value) { if (value < 0M || value > 100M) { throw new ArgumentException ("value", "value is expected to be in the range 0..100"); } } }
An operator is just a convenience operator, allowing an implicit conversion from ValidPercent ==> Percent (this is always safe). Partial_ValidateValue performs the actual check.
This should give you a few starting points when you think about whether the T4 suits you.
Hope this helps ...