Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4 templates: any way to make ToStringWithCulture() convert null to string.Empty instead of throwing exception?

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?

like image 563
moarboilerplate Avatar asked May 14 '15 15:05

moarboilerplate


1 Answers

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:

  1. Create a new base class for the template, for example TemplateBase.cs
  2. 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.

  3. Add the following declaration to TemplateBase.cs:

    /// <summary>
    /// Required to make this class a base class for T4 templates
    /// </summary>
    public abstract string TransformText();
    
  4. 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.

  5. 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/

like image 95
Koja Avatar answered Sep 24 '22 19:09

Koja