I am trying to create a method that accepts multiple types of controls – in this case Labels and Panels. The conversion does not work because IConvertible doesn’t convert these Types. Any help would be so appreciated.
Thanks in advance
public void LocationsLink<C>(C control)
{
if (control != null)
{
WebControl ctl = (WebControl)Convert.ChangeType(control, typeof(WebControl));
Literal txt = new Literal();
HyperLink lnk = new HyperLink();
txt.Text = "If you prefer a map to the nearest facility please ";
lnk.Text = "click here";
lnk.NavigateUrl = "/content/Locations.aspx";
ctl.Controls.Add(txt);
ctl.Controls.Add(lnk);
}
}
Wouldn’t you want a where constraint on control like so:
The
whereconstraint forcescontrolto be of type WebControl so no conversion is necessary. Because of thewhereconstraint, you know thatcontrolis a class and can be compared to null and that it has a Controls collection.I also change the code to throw an exception if
controlis null. If you really just wanted to ignore situations where a null argument is passed, then simply change thatthrow new ArgumentNullException("control");toreturn null;. Given the compile constraint, I would think that passing a null to your routine would be unexpected and should throw an exception however I do not know how your code will be used.