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?
source to share
Mnaumov's solution. Modify the base template class
public string ToStringWithCulture(object objectToConvert)
{
if (objectToConvert == null)
return "";
...
}
source to share
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:
- Create a new base class for the template like
TemplateBase.cs
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 namedYourTemplateBase
and contains (among other things) thepublic class ToStringInstanceHelper
one mentioned in the question.Add the following ad 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 to
YourTemplate.tt
:<#@ template language="C#" Inherits="TemplateBase" #>
After this change, your template will no longer generate the base class.
Make the following edit in
ToStringInstanceHelper
nested underTemplateBase.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/
source to share