Cool feature starting with Visual Studio 2008Edit

Let’s say that you wanted to create a class that looks like this:

public class SimpleClass
		public int Property0 { get; set; }
		public int Property1 { get; set; }
		public int Property2 { get; set; }
		public int Property3 { get; set; }
		public int Property4 { get; set; }
		public int Property5 { get; set; }
		public int Property6 { get; set; }
		public int Property7 { get; set; }
		public int Property8 { get; set; }
		public int Property9 { get; set; }

That’s 10 properties. If you wanted 15, you have to add 5 more lines above. Or do you? What if you could write a loop in C# that goes from 1 to 15 and creates the above source lines. It’s actually a lot more convenient to do this than you think. All you have to do is add a new text file to your C# project, then rename the .txt file to .tt. Then in the contents of .tt, add this:

public class SimpleClass
	<# for (int i = 0; i < 10; i++)
	{ #>
	public int Property<#= i #> { get; set; }
	} #>		

So if you want to change the 10 to 15, just change the highlighted number.

Visual Studio automatically creates a .cs file under the .tt file. In the Solution Explorer, it looks like this:

tbd fix this:

Now if you want to know why you’d do this, I’d say that’s an exercise left for the user – there’s plenty written on what can be done with meta-programming. The primary benefit is performance.

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.