Beatles1692
Beatles1692

Reputation: 5330

How to generate array type using a given type?

I am working on a code generator written in C#. This code generator reads a xml file and generate a .cs file. So far we have assumed that all fields are string which is not true and I have changed the code so it can generate a type according to the specified type in our xml :

<MyField>
   <Name>Name</Name>
   <Type>String</Type>
</MyField>

But there might be some fields that can have more than one values (Multiselectable fields) that have another attribute (Options for example) that list all possible options. What I would like to do is to generate the array type for any given type .So that I can process my fields first and if there are some fields optional I can convert their type to an array.

Here's what I want to do :

Type fieldType=typeof(string);
Type fieldType=GetArrayTypeof(fieldType); 

How should I implement GetArrayTypeOf function ?

Upvotes: 2

Views: 122

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

To get type from its string name you can use Type.GetType method.

To get array type from item use Type.MakeArrayType instance method:

 string itemTypeName = "System.Int32";

 Type itemType = Type.GetType(itemTypeName);

 Console.WriteLine(itemType.MakeArrayType());

Upvotes: 2

Related Questions