Vajura
Vajura

Reputation: 1132

C# syntax for passing a class type as argument?

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.

Upvotes: 0

Views: 111

Answers (2)

Dilip Nannaware
Dilip Nannaware

Reputation: 1480

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);
    }

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

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));
}

Upvotes: 10

Related Questions