A simple approach for keeping book snippets in sync for C#
A simple approach for keeping book snippets in sync for C#
Submitted by Jonathan de Halleux on Thu, 11/10/2007 - 07:41.When someone is writing a book that contains code snippets, the question of (automatically) keeping those in sync quickly becomes very imporant. There's already lots of different solutions to this problem (every author has probably it's own), here's yet another one for C# that we've developed to author the Pex documentation.
Goals
A couple things that we wanted to acheive with this tool:
- snippets are always compilable and run as expected,
- snippets can be full classes, methods or even partial statements
- simple :)
'#region' based solution
This solution uses the #region directive to define a snippet. The region describe contains the snippet name, which will be used to dump it into a file. For example, given this piece of C#,
...
#region snippet StackExamplePart3
stack.Push(new object);
#endregion
...
Our parse will extract the code in the region and write it to StackExamplePart3.tex, which gets pulled in our LaTeX scripts.
\begin{verbatim}
stack.Push(new object);
\end{verbatim}
That's it?
Yes, you can author snippets that stay compilable and up to date:
- we can author all the snippets in Visual Studio and we are sure they always compile
- it's very easy to parse the #region's (left as exercise ;))
- #region are very flexible in terms what they contain so we can have snippets containing partial methods, statement, etc...
- the scheme aslo supports nested regions which is usefull when one explains an example line by line, and integrate the entire sample at the end. For example, DeclaringUnitTest is a 'sub'-snippet of UnitTest:
#region snippet UnitTest
#region snippet DeclaringUnitTest
[TestMethod]
void Test(int i)
#endregion
{
}
#endregion
- we can integrate our snippets in unit tests and verify they work as expected
- the tool can be integrated into the build process as a post-command build
This posting is provided "AS IS" with no warranties, and confers no rights.
