I faced a problem where I need to extends System.Web.UI.WebControls.Control Classes and it is Childs (TextBox , Button , …) so I can add some extra properties and methods to be shared across all the Control class family .
We can simple create Wrapper Class like this to do the task
public class ControlWrapper
{
public Control OriginalObject;
public ControlWrapper(Control obj)
{
OriginalObject = obj;
}
//I need to add this method to all Control Family
public string PrintIt()
{
return "Print This :" + this.OriginalObject.ClientID;
}
}
The problem with this module, I will lose access to the original property for the child class , I cannot access TextBox special property without casting.
What is wrong with casting!? .. nothing really wrong with it , but I am building component to be easier for the rest of the developer to work with. So I need a way to maintain the original type properties!
Okie .. the Generics provide nice solution about that , just watch the following implementation
//Factory Class used to create extended controls
public class ExtendedControlFactory
{
public ExtendedControl<T> ExtendControl<T>(T obj) where T : Control
{
ExtendedControl<T> newObj = new ExtendedControl<T>(obj);
return newObj;
}
}
public class ExtendedControl<T> where T : Control
{
public ExtendedControl(T objIn)
{
this.OriginalObject = objIn;
}
//this property gave caller access to the wrapped object original property
public T OriginalObject;
//I need to add this method to all Control Family
public string PrintIt(){
return "Print This :" + this.OriginalObject.ClientID;
}
}
Now , just gave a look to the client code
//Create Factory Instance
ExtendedControlFactory controlFactory = new ExtendedControlFactory();
//Create Extended Control Instance
ExtendedControl <Button> extdCon = controlFactory.ExtendControl<Button>(new Button());
//Note those properties are specific property for the Button Control , they are not exist on the parent Control class.
extdCon.OriginalObject.ToolTip = "ToolTip";
extdCon.OriginalObject.Text = "Text";
//Note this is the extra method added using the Wrapper
extdCon.PrintIt();
now notice , you have access to the original object property methods , and the extra method added by the Wrapper.
I found this trick a nice one , I just want to share it with the rest of you coders
Enjoye …