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 "";

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to T4 Templates and Null in Expression block

  1. richard578 says:

    Not really sure how this is a solution. The T4 template will re-generated the base class every time you change the template and hit save. Further more, the ToStringWithCulture method is not marked as virtual, so there is not way to override it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s