Extending multiple Controls

  • Thread starter Thread starter Wolfgang Hanke
  • Start date Start date
W

Wolfgang Hanke

Hello,

I want to extend multiple Controls like TextBox, Label, ComboBox etc. with
the same new featureset (for Example all need a Method getSomething())
Because I cant alter their Base-Class I have to write one new class for each
Control like MyTextBox, MyLabel, MyComboBox implementing
IMyControlInterface.
The Code for each Control is exactly the same but C# offers no way to
"include" some code.

Do I really have to write all the code into every Class? Isnt their an
elegant way to achieve this?

Any help greatly appreciated!

Best regards,
Wolfgang Hanke
 
If the code is the same... would it suffice to just have a method that
accepts Control? Or is it something specific you are doing?

Well, C# 3 extension methods could do what you describe; you'd still
need separate extension methods for each type, but they could all call
into the same implementation:

public static class ControlExt {
public static void DoSomething(this Label label)
{DoSomethingImp(label);}
public static void DoSomething(this TextBox textBox)
{DoSomethingImp(textBox);}
// etc
static void DoSomethingImp(Control control) {
// your code
}
}

Now against a Lable (for example) you will be able to use:
label1.DoSomething();

Marc
 
Thank you, I did not know about those extension methods. I will have a
closer look at them even though it sounds as if you should not use them
extensively...

Wolfgang
 
Note that extension methods are just compiler trickery to make it *seem*
like there is an instance method (DoSomething) on the nominated control.
In reality they are just static methods that accept the instance as the
first argument, and they need the C# 3 compiler. But it might help...

Marc
 
Back
Top