Mishaka
Mishaka

Reputation: 1

C# Create a general method parameter

I have program with 2 classes and i'm trying to create a method, which formats some System.Windows.Forms objects of the other class.

This is my code:

    internal void Format(Panel component, int width, int height, int x, int y)
    {
        component.Width = width;
        component.Height = height;
        component.Left = x;
        component.Top = y;
    }

    internal void Format(GroupBox component, int width, int height, int x, int y)
    {
        component.Width = width;
        component.Height = height;
        component.Left = x;
        component.Top = y;
    }

    internal void Format(Button component, int width, int height, int x, int y)
    {
        component.Width = width;
        component.Height = height;
        component.Left = x;
        component.Top = y;
    }

I can create the same methods (with different object parameter) for all required object types, but maybe there is a way to create it with just one method with 'general/overall/common' parameter for all object types.

Upvotes: 0

Views: 212

Answers (1)

jegtugado
jegtugado

Reputation: 5141

Try using Control as your parameter data type since all controls inherit from this class.

internal void Format(Control component, int width, int height, int x, int y)
{
    component.Width = width;
    component.Height = height;
    component.Left = x;
    component.Top = y;
}

Upvotes: 1

Related Questions