I am creating a code generator that generates classes from a schema. A type from such a schema could have members that are duplicate, allowing multiple lines of text or something like that. I want to solve that by creating a property on first occurence, and then promote that property to an array on subsequent occurrences.
To my surprise, when emitting the class, I can see that i have a member field and property of the base type, and not of type Array!
The part of that code where I promote a backingfield to an Array is shown here:
var memberFieldType = new CodeTypeReference(typeof(Array)) { ArrayElementType = property.MemberField.Type };
property.MemberField = new CodeMemberField(memberFieldType, property.MemberField.Name);
property.MemberField.InitExpression = new CodeArrayCreateExpression(memberFieldType, property.Count);
Further investigation taught me that typeof(Array).IsArray
returns false
, and that causes the CSharpCodeGenerator to generate the wrong type for the memberfield and property.
Does anyone have an idea why typeof(Array).IsArray
returns false?
thanks for responses.
I solved the issue I had by using another constructor for the CodeTypeReference instance that identifies the type of the property (and backingfield)
Originally, I created the instance using:
var memberFieldType = new CodeTypeReference(typeof(Array)) { ArrayElementType = property.MemberField.Type };
I expected typeof(Array)
to return true and then with the ArrayElementType propeprty initialized to the correct array element type, it should provide the right CodeTypeReference
instance, but that wasn't the case.
The sourcecode of CodeTypeReference
show that the constructor I used just does a check on the type parameter using the IsArray property of the type passed in. Because that returns false, the type is never identified as an array property at all and the ArrayElementType property is discarded.
I then changed the code to:
var memberFieldType = new CodeTypeReference(property.MemberField.Type, 1);
That constructor takes a CodeTypeReference as first parameter, and a rank as second parameter that specifies the dimensions of the array, automatically transforming the resulting CodeTypeReference into the type I needed.
With that approach, all array properties and backingfields are beeing emitted as desired