Erik Z
Erik Z

Reputation: 4780

How to fill in constructor parameters in runtime?

I want to create an instance of a type, but I don't know the type until runtime.

How can I get the constructor's required parameters to display them to the user in a WPF-window?

is there something like Properties Window in Visual Studio to be used?

Upvotes: 2

Views: 297

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100565

Here is the search - http://www.bing.com/search?q=c%23+reflection+constructor+parameters - top answer is ConstructorInfo with sample:

public class MyClass1
{
    public MyClass1(int i){}
    public static void Main()
    {
        try
        {
            Type  myType = typeof(MyClass1);
            Type[] types = new Type[1];
            types[0] = typeof(int);
            // Get the public instance constructor that takes an integer parameter.
            ConstructorInfo constructorInfoObj = myType.GetConstructor(
                BindingFlags.Instance | BindingFlags.Public, null,
                CallingConventions.HasThis, types, null);
            if(constructorInfoObj != null)
            {
                Console.WriteLine("The constructor of MyClass1 that is a public " +
                    "instance method and takes an integer as a parameter is: ");
                Console.WriteLine(constructorInfoObj.ToString());
            }
            else
            {
                Console.WriteLine("The constructor of MyClass1 that is a public instance " +
                    "method and takes an integer as a parameter is not available.");
            }
        }
        catch(Exception e) // stripped out the rest of excepitions...
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}

Upvotes: 1

Matten
Matten

Reputation: 17603

Have a look at the ParameterInfo objects which can be obtained from the reflected type:

Type type = typeof(T); 
ConstructorInfo[] constructors = type.GetConstructors();

// take one, for example the first:
var ctor = constructors.FirstOrDefault();

if (ctor != null)
{
    ParameterInfo[] params = ctor.GetParameters();

    foreach(var param in params)
    {
         Console.WriteLine(string.Format("Name {0}, Type {1}", 
             param.Name,
             param.ParameterType.Name));
    }
}

Upvotes: 3

Related Questions