aronmatthew
Well-known member
- Joined
- Aug 5, 2019
- Messages
- 46
- Programming Experience
- Beginner
I'm trying to create a class of type T where T: Control. The only problem is that when creating a class object of type T where T inherits from Control the cast is seemingly impossible.
although in theory it could be possible in this case to bypass the template method and pass a Type to the constructor to create an instance of any derivation of Control which should prevent the need of such a cast
C#:
internal class Class1<T> where T: Control
C#:
Class1<RichTextBox> textControl = new Class1<RichTextBox>();
Class1<Control> control = textControl;
C#:
try
{
if (controlType.IsSubclassOf(typeof(Control)))
Control = Activator.CreateInstance(controlType) as Control;
else
throw new Exception("invalid type");
}
catch(Exception ex)
{
Control = null;
}
Last edited: