Skip to content
mnaoumov.dev
Go back

T4 Templates and Null in Expression block

Another annoying issue with T4 templates is its support for nulls.

If you have template

<#@ Template Language="C#" \#>
<#@ Output Extension=".txt" \#>
Null string: "<#= (string) null \#>"

Both design-time and runtime templates will fail with

An expression block evaluated as Null
System.ArgumentNullException: Value cannot be null.
Parameter name: objectToConvert
   at Microsoft.VisualStudio.TextTemplating.ToStringHelper.ToStringWithCulture(Object objectToConvert)

And this is very annoying because sometime you are calling external functions and you don’t want to check for nulls all the time.

<#@ Template Language="C#" \#> Null string: "<#= (object) Helper.MyFunction() ?? "" \#>"

It is unacceptable.

So I decided to change base template class and handle ‘null’ case.

For runtime templates I modify base class which we created previously and fix ToStringWithCulture method

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

Share this post on:

Previous Post
T4 Design-Time templates base class
Next Post
Useful Dictionary extensions I am always using