I’m trying to create a class like Windows Form, which will have multiple new features. It’s simply going to be a “better” version of Form, making my work easier on this exact program. Here’s what I have so far:
public class SuperForm : Form
{
protected abstract void OnSizeChanged(object sender, EventArgs e);
public SuperForm()
{
this.SizeChanged += OnSizeChanged;
}
}
Not much, it only makes sure every Form will have to define OnSizeChanged which will be called automatically when size changes, but there’s going to be more.
What I need next is a method which takes a class/type as it’s parameter and initializes a new object of that type, automatically adds it to Controls and then returns the object. Here’s an example code (not working) on how I would like it to be like:
public cls NewControl(ClassType cls) // This obviously doesn't work.
// I need it to return an object of type "cls" parameter.
{
cls newControl = new cls();
this.Controls.Add(newControl);
return newControl;
}
I know ClassType is not a valid type, that’s why I need help.
And then I could basically call it like this:
Button b = this.NewControl(Button);
Which would return a new button and also add it to this.Controls. I might eventually need to do more of these common tasks when a control is initialized, so that’s why I’d like to have it in it’s own method.
Is this possible in C#? If not, are there any workarounds? One way would be to define a method for each class inheriting from Control like this:
public Button NewControl(Button b);
public TextBox NewControl(TextBox tb);
public ListBox NewControl(ListBox lb);
But it doesn’t seem like a valid option to me.
It sounds like you want to make a generic method, with a couple of constraints on the type parameter:
Here the
T : Controlconstraint makes sure that you’re creating a control, so that you’ll be able to useControls.Add. TheT : new()constraint makes sure the type argument has a public parameterless constructor, so that you can callnew T().To create a TextBox, for example, you would call the function like this:
(I’ve renamed the method for what I believe to be clarity, btw.)