T4 templates: Any way to force ToStringWithCulture () to convert null to string.Empty instead of throwing an exception?

When I provide an object to a T4 template with null properties, unless I explicitly write the <#= obj.Property ?? string.Empty #>

method ToStringWithCulture(object objectToConvert)

that is generated for the template, it throws a ArgumentNullException

if the property is null. Is there some neat or elegant way to override this behavior so that I don't have to overflow null collage across all my templates?

+4


source to share


2 answers


Mnaumov's solution. Modify the base template class



public string ToStringWithCulture(object objectToConvert)
{
    if (objectToConvert == null)
        return "";
    ...
}

      

0


source


Lloyd's answer is mostly correct, but incomplete. You will have to override the base class of the template so that the change persists even after editing the template. Here's how:

  1. Create a new base class for the template like 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 in the .tt template in Visual Studio. It is named YourTemplateBase

    and contains (among other things) the public class ToStringInstanceHelper

    one mentioned in the question.

  3. Add the following ad 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 to YourTemplate.tt

    :

    <#@ template language="C#" Inherits="TemplateBase" #>
    
          

    After this change, your template will no longer generate the base class.

  5. Make the following edit in ToStringInstanceHelper

    nested under TemplateBase.cs

    :

    public string ToStringWithCulture(object objectToConvert)
    {
        if (objectToConvert == null)
            return "";
        ...
    }
    
          



Credit for multiums: https://mnaoumov.wordpress.com/2012/09/27/t4-runtime-templates-base-class/

0


source







All Articles