Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a generic class using CodeDOM whose generic parameter is a type that I created?

Tags:

c#

codedom

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.

like image 937
Bruno Brant Avatar asked Feb 28 '12 22:02

Bruno Brant


2 Answers

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));
like image 62
svick Avatar answered Oct 07 '22 11:10

svick


The chosen answer didn't work for me for whatever reason, but this did:

var listType = new CodeTypeReference("List", new[] { new CodeTypeReference(typeof(int)) });

See documentation here.

like image 36
sbl03 Avatar answered Oct 07 '22 11:10

sbl03