views:

22

answers:

1

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);
        }
    }
+3  A: 

Wouldn't you want a where constraint on control like so:

public void LocationsLink<C>(C control) where C : WebControl
{
    if (control == null)
        throw new ArgumentNullException("control");

    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";
    control.Controls.Add(txt);
    control.Controls.Add(lnk);
}

The where constraint forces control to be of type WebControl so no conversion is necessary. Because of the where constraint, you know that control is 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 control is null. If you really just wanted to ignore situations where a null argument is passed, then simply change that throw new ArgumentNullException("control"); to return 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.

Thomas
Thank you for the answer. Can you take it one step further and show what else I would do in the method in order to facilitate the conversion? In the mean time I will be researching constraints.
Praesagus
I expanded my post for you.
Thomas
Thank you for taking the time to explain it. You just gave me another great tool.
Praesagus