0

I want to in a sense generalize creation of Controls for ease of use.

public static Control mkC(TYPE type, int x, int y, int w, int h)
{
    Control c;
    c = new type();
    c.Location = new Point(x, y);
    c.Size = new Size(w, h);
    return (type)c;
}

main()
{
    TextBox t = mkC(TextBox, 1,1,100,100);
}

But i dont know the exact way of doing what i want to do.

2 Answers 2

10

Use Generics

public static T CreateInstance<T>(int x, int y, int w, int h) where T : Control, new()
{
    T c = new T();
    c.Location = new Point(x, y);
    c.Size = new Size(w, h);
    return c;
}

Then use it as

main()
{
    TextBox t = CreateInstance<TextBox>(1,1,100,100);
}

Also, I'll reduce the number of parameters by passing a Rectangle struct.

public static T CreateInstance<T>(Rectangle rect) where T : Control, new()
{
    T c = new T();
    c.Location = rect.Location;
    c.Size = rect.Size;
    return c;
}

Then use it as

main()
{
    TextBox t = CreateInstance<TextBox>(new Rectangle(1,1,100,100));
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Neel Spelling mistake dude ;)
0

Mentioning two options here:

Below option is on the same line on which you have mentioned. You need to pass the type as argument and then use CreateInstance() method of type. Also will have to cast the instance to specific control. public Control CreateControlInstance(Type type, int x, int y, int w, int h) { Control c = (Control) Activator.CreateInstance(type); c.Location = new Point(x, y); c.Size = new Size(w, h); return c; }

    private main()
    {
        TextBox t = (TextBox) CreateControlInstance(typeof (TextBox), 1, 1, 100, 100);
    }

Also you can write the generic function like mentioned below:

    public static T CreateControlInstance<T>(int x, int y, int w, int h) where T : Control, new()
    {
        T c = new T();
        c.Location = new Point(x, y);
        c.Size = new Size(w, h);
        return c;
    }

    private main()
    {
        TextBox t = CreateControlInstance<TextBox>(1, 1, 100, 100);
    }

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.