How can I get the list of elements and datatypes of an array of an object in c# with reflections?
Scenario: I have a method with an array parameter in my web service (asmx). Using reflection I am reading the method parameters and loop through the properties. Here is my code:
Example:
I have a webservice http://localhost/services/myservice.asmx. It has a method string GetServiceData(context mycontext).
context class has following properties
- string name
- Account[] accounts
Account in turn has
- string acct_name
- string acct_address
I need to read the service dynamically to generate the following output
<GetServiceData>
<mycontext>
<name>string</name>
<accounts>
<acct_name>string</acct_name>
<acct_address>string</acct_address>
</accounts>
</mycontext>
</GetServiceData>
To do so I am dynamically reading the MethodInfo and get all the parameters. Then I loop through the parameters to get the list of all the properties and the datatypes. If there is an array element in the properties then I need to get all the elements of that array element.
Solution (Thanks to Ani)
foreach (MethodInfo method in methods)
{
sb.Append("<" + method.Name + ">");
ParametetInfo parameters = method.GetParameters();
foreach(ParameterInfo parameter in parameters)
{
sb.Append("<" + parameter.Name + ">");
if (IsCustomType(parameter.ParameterType))
{
sb.Append(GetProperties(parameter.ParameterType));
}
else
{
sb.Append(parameter.ParameterType.Name);
}
sb.Append("</" + parameter.Name + ">");
}
sb.Append("</" + sMethodName + ">");
}
GetProperties() method reads the type and actually loop through each property and add it to string object. In this method I want to check if the property is an array then get all the elements and type for it.
public static string GetProperties(Type type)
{
StringBuilder sb = new StringBuilder();
foreach(PropertyInfo property in type.GetProperties())
{
sb.Append("<" + property.Name + ">");
if (property.PropertyType.IsArray)
{
Type t = property.PropertyType.GetElementType();
sb.Append(GetProperties(t));
}
else
{
sb.Append(property.PropertyType.name);
}
}
sb.ToString();
}