It seems I still don’t “get” generics … I want a general function to load a user control which inherently calls Page.LoadControl() but I am getting the error above when trying to make it work.
Here is a mock up of the code I use to load the control:
MyControl Ctrl = MyUtilClass.LoadControl(Page, "MyControl");
and then in MyUtilClass:
internal static T LoadControl<T>(Page P, string ControlName)
{
return (T)P.LoadControl(String.Format("~/{0}{1}.ascx", WebGlobals.cControlDir, ControlName));
}
I am obviously doing something wrong but my understanding was the compiler would look at the type of var I am trying to assign the result of this function to and be able to cast the result as that type.
I think you need to constrain your generic function to
Controls only, otherwiseTis too generic for your purposes.EDIT
You could do this but I’m not sure its worth the extra complexity over the non generic approach in Daniel Hilgarth’s answer.
calling like this