Reputation: 4399
I've written some code to generate .NET types from XML schemas coming out of our CMS. This is going smoothly and producing the results I am expecting.
Now I want to customize the default (parameterless) constructor of a generated type. I have some code that looks like:
CodeNamespace codeNamespace = new CodeNamespace("MyNamespace");
// import type mappings from schema
// export type mappings into codeNamespace
CodeTypeDeclaration codeType = codeNamespace.Types.First();
At this point, I can successfully modify codeType
; adding/removing attributes, properties, etc.
However, inspecting the Members
property of the codeType
indicates that there is not yet a default constructor defined. Sure I could add one; but when I go to write out the code string (using CSharpCodeProvider.GenerateCodeFromNamespace
), another default constructor is added to the output (in this case, for setting some default values on fields derived from the schema).
What I'm trying to do is basically insert a call to a method inside the default constructor (a method that I can successfully add to codeType
as per above).
(How) can I deal with the fact that when I write out the code string, a default constructor (that wasn't present in the Members
collection before) is inserted?
Upvotes: 1
Views: 326
Reputation: 4399
Well, I feel a bit silly...
I confused myself during debugging - was looking at a codeType
that did not define a default constructor and comparing to generated source with a type that did contain a default constructor.
I was able to use code similar to the following to handle both cases:
var ctor = codeType.Members
.Cast<CodeTypeMember>()
.SingleOrDefault(m => m.GetType() == typeof(CodeConstructor));
if (ctor == null)
{
//codeType didn't define a default constructor, so create one
ctor = new CodeConstructor() { Attributes = MemberAttributes.Public };
}
else
{
//codeType did define a default constructor, remove it before modifying
codeType.Members.Remove(ctor);
}
//make some modifications to ctor
//add ctor to the codeType
codeType.Members.Add(ctor);
Upvotes: 1