1

I am trying to generate some generic code that can create C# objects from text generated by another system. The object is to be used for a method call - the method call is also going to be done by reflection. When I am creating this method parameter object, I could not figure out how to instantiate and assign values to a property that is array type. I can use the setValue to assign to "name" in the code sample below, but how to assign values to the array?

class Car {
    public string name { get; set; }
    public Door[] doors { get; set; }
}

class Door {
    public int index { get; set; }
    public bool isDusty { get; set; }
}

public object createMethodParameter(Vehicle<T> v)

    object methodParameter;

    Type type = v.GetType();

    PropertyInfo[] properties;
    MethodInfo[] mi = type.GetMethods();

    ParameterInfo[] pi;

    foreach (var method in mi)
    {
        if ("create".Equals(method.Name.ToLowerInvariant())) // look for the create method
        {
            pi = method.GetParameters();
            foreach (var param in pi)
            {
                returnValue = Activator.CreateInstance(param.ParameterType);
                properties = param.ParameterType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType.IsArray)
                    {
                        // how to create the doors array on the car??
                    }
                    else
                    {
                        property.SetValue(methodParameter, "Porsche", null);
                    }
                }
            }
        }
    }
    return methodParameter;
}
2
  • 1
    Well, you need to get the type of the array, call Array.CreateInstance or something similar, fill the array, set the property, etc. Which part are you stuck on? Commented Sep 19, 2016 at 15:07
  • The "Array.CreateInstance" part. I thought I needed the Activator class for that. SLaks answer helped me. I will accept it in a few minutes. Commented Sep 19, 2016 at 15:18

1 Answer 1

3
Array.CreateInstance(property.PropertyType.GetElementType(), 4)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.