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

2

8

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.

Baron answered 28/2, 2012 at 22:5 Comment(2)
How would passing the Name property of the type declaration be any different from using the name property of typeof(List<>) ?Erine
@Erine typeof(list<>) relies on reflection to retrieve the name; but I see your point... I could use list_type.Name, right?Baron
E
7

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));
Embrangle answered 28/2, 2012 at 23:46 Comment(2)
The problem is that I'd like to do TypeArguments.Add(my_type_declaration). I think I will have to do with using the name of my type anyway. Thanks!Baron
My issue was that XSD elements were generated as Array's instead of List<>. This fixed my problem! Tnx.Cruciferous
E
1

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.

Evalynevan answered 7/1, 2015 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.