6.9. Generating Code That Is No Longer in Your Main Code Paths
Problem
Occasionally, as a developer, you run into a situation in which it would be handy to be able to regenerate your class based on a set of data that can change. You need to be able to do this without destroying all of the logic you have already created or causing yourself a painful merge between an old and a new class file.
Solution
Write a utility that can regenerate the code that is dependent on external data and keep the generated code in a separate file that defines a partial class. To demonstrate this, we have created a Visual Studio 2008 add-in called PartialClassAddin in the sample code that will allow you to enter a class name and then select which attributes to apply to the class. This is a standard add-in generated by selecting the add-in template from the project wizard. Its main dialog box is shown in Figure 6-1.
Enter a class name, MyNewClass, select the System.CLSCompliantAttribute and the System.SerializeableAttribute from the list, and click the OK button. This generates the MyNewClass_Attributes.cs file with the following in it:
// Using directives
using System;
namespace NamespaceForMyNewClass
{
#region Attributes
[System.CLSCompliant(true)]
[System.Serializable()]
#endregion // Attributes
public partial class MyNewClass
{
public MyNewClass()
{
}
}
}
Figure 6-1. Attributed Class Wizard from partial class ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access