This statement will change the position of a form object.
lblMessage.Location = new Point(0,0);
I would like to write a generic template function that can position any form object.
I came up with this, but it is invalid:
public void ChangePosition<T>(T form_object)
{
form_object.Location = new Point(0,0);
}
and I call it like this:
ChangePosition(lblMessage);
Error: 'T' does not contain a definition for 'Location' and no extension method 'Location' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)
Do I need to mention some kind of interface on the template function? How do I call an extension method on a generic type?
You don't need a generic method, you can do it this way:
The base class for all controls of your form is
Control
which hasLocation
property.What you can do is add
where T : Control
onto the definition of the function.Control
is the highest point in the hierarchy that defines thePoint Location
.