Can I "Escape" C# Keywords?

Jan 8, 2012 at 3:39 PM


I am trying to build .cs files from templates. How can I escape C# keywords? For example:

public DbSet GetDbSet<T>()
            @foreach (var dbSet in Model.DbSets)
                if (typeof(T) == typeof(@dbSet.ModelName))
                    return @dbSet.Name;

            throw new ArgumentException("Unknown Entity Model");

The above code is a method inside my template. GetDbSet<T> will be fine, but anything inside the @foreach gets treated as though it were code. I'd liek to escape it - sending the text directly to the new .cs file. Is this possible?


Jan 9, 2012 at 1:40 AM

Here is a simple test you can try:

class TestProperty
            public string PropertyType { get; set; }
            public string PropertyName { get; set; }
string testTemplate = @"Testing 123 @Model.Name
@foreach (var p in Model.Properties)
            public @p.PropertyType @p.PropertyName { get; set; }

            var p1 = new TestProperty { PropertyName = "P1", PropertyType = "string" };
            var p2 = new TestProperty { PropertyName = "P2", PropertyType = "int" };

            MessageBox.Show(Razor.Parse(testTemplate, new { Name = "WallaWalla", Properties = new[] { p1, p2 } })); 

It will throw a TemplateCompilcationException with this error:

error CS1513: } expected

I tried using the @(@keyword) syntax as found here: but to no avail. Help, please!