I have written an extension method which finds a control depending on the Type passed as an indexer to the function. Here is my extension method.
public static T FindControlByType<T>(this Control childCnt, string Id = "")
{
foreach (Control item in childCnt.Controls)
{
if (item is T)
{
if (Id == "")
{
return (T)Convert.ChangeType(item, typeof(T));
}
if (item.ID.Contains(Id))
{
return (T)Convert.ChangeType(item, typeof(T));
}
}
}
//return T
}
I want to return control of Type T. How do i achieve this?
If you add a generic constraint to restrict
Tto be of typeControl, then you don’t need theChangeTypecalls. The cast is enough.