Lambda Expressions in T4 Templates

Despite being quite well hidden, Visual Studio's T4 templating engine is a great feature.

However, whilst putting together a T4 template in Visual Studio 2008, throwing in a simple lambda expression such as:

<#=string.Join(",", aList.ConvertAll(field => field.Name).ToArray())#>

Can cause the code generation to fail. As it turns out, the T4 template language is set to C# 2.0 by default.

This can easily be fixed by changing the template directive at the head of the template file to C#v3.5:

<#@ template language="C#v3.5" hostspecific="True" #>

Ideally this would be the default in a C# 3.5 project, but I'm sure there's a reason for this...

Leave a Reply

Your email address will not be published. Required fields are marked *