user3447537
user3447537

Reputation: 37

C# Generic Method, create controls with arguments

I was wondering if its possible to create a Control (Winform) by passing the arguments of the control as a anonymous type.

E.G

Create<Label>(new {Text = "Test"});

public void Create<T>(object args) where T : Control
{
   T Control = new T(args);
   return Control;
}

Upvotes: 2

Views: 295

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use Reflection, Control class has only a parameterless constructor.So you need to set each property separately

 public T Create<T>(object args) where T : Control, new()
 {
        T control = new T();
        var propertyValues = args.GetType()
            .GetProperties()
            .ToDictionary(x => x.Name, x => x.GetValue(args));
        var controlType = typeof(Control);
        foreach (var kvp in propertyValues)
        {
            var prop = controlType.GetProperty(kvp.Key);
            prop.SetValue(control, kvp.Value);
        }
        return control;
 }

Usage:

Label lbl = Create<Label>(new { Text = "bla bla bla..", BackColor = Color.Blue });

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102753

You could do it by passing in an Action delegate, like this:

Create<Label>(label => label.Text = "Test");

public T Create<T>(Action<T> setup) 
    where T : Control, new()
{
    T control = new T();
    setup(control);
    return control;
}

If you had multiple properties, the syntax would be:

Create<Label>(label => {
    label.Text = "Test";
    label.Color = Colors.Black;
});

Alternately, you could have multiple parameters:

Create<Label>(label => label.Text = "Test", label => label.Color = Colors.Black);

public T Create<T>(params Action<T>[] actions) 
    where T : Control, new()
{
    T control = new T();
    if (actions != null)
        foreach (var action in actions)
            action(control);
    return control;
}

Upvotes: 3

Related Questions