When I provide an object to a T4 template with nullable properties, unless I explicitly write <#= obj.Property ?? string.Empty #>
the ToStringWithCulture(object objectToConvert)
method that is generated for the template throws an ArgumentNullException
if the property is null. Is there any neat or elegant way to override this behavior so that I don't have to pepper null coalescing all over my templates?
lloyd's answer is basically correct but incomplete. You will have to override the base template class for the change to persist even after you edit your template. Here's how:
TemplateBase.cs
Copy the contents of your current auto-generated template base class to TemplateBase.cs
. The auto-generated base class can be found under your .tt template in Visual Studio. It's called YourTemplateBase
and it contains (among other things) the public class ToStringInstanceHelper
mentioned in the question.
Add the following declaration to TemplateBase.cs
:
/// <summary>
/// Required to make this class a base class for T4 templates
/// </summary>
public abstract string TransformText();
Add the base template declaration in YourTemplate.tt
:
<#@ template language="C#" Inherits="TemplateBase" #>
After this change, your template will no longer generate a base class.
Make the following edit in ToStringInstanceHelper
nested inside TemplateBase.cs
:
public string ToStringWithCulture(object objectToConvert)
{
if (objectToConvert == null)
return "";
...
}
Credit to mnaoumov: https://mnaoumov.wordpress.com/2012/09/27/t4-runtime-templates-base-class/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With