Reputation: 8564
I have a class that I created using CodeDOM:
CodeTypeDeclaration some_class = new CodeTypeDeclaration("SomeClass");
// ... properties and methods creation elided
I want to create a List of the "SomeClass" type. However, I can't seem to do so:
var list_type = new CodeTypeReference(typeof (List<>).Name, ??? some_class ???);
var member_field = new CodeMemberField(list_type, field_name)
{
Attributes = MemberAttributes.Private,
};
CodeTypeReference doesn't accept a CodeTypeDeclaration
, which is what I need. What can I do? I don't want to pass the class name as a string, since this could lead to errors.
Upvotes: 8
Views: 3693
Reputation: 72
The chosen answer didn't work for me for whatever reason, but this did:
var listType = new CodeTypeReference("List", new[] { new CodeTypeReference(typeof(int)) });
Upvotes: 1
Reputation: 244968
I'm afraid you can't. There doesn't seem to be any way to create a CodeTypeReference
from a CodeTypeDeclaration
. I think that's because CodeTypeDeclaration
does not know what namespace it's in, so there is no safe way to do that.
On the other hand, when creating a CodeTypeReference
to generic type, you don't need to use the name of the generic type:
var listType = new CodeTypeReference(typeof(List<>));
listType.TypeArguments.Add(typeof(int));
Upvotes: 7