casting from class<Base> to class<Sub>

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.
C#:
 internal class Class1<T> where T: Control
C#:
 Class1<RichTextBox> textControl = new Class1<RichTextBox>();
 Class1<Control> control = textControl;
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#:
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:
Works for me:
1738196229741.png

C#:
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Configuration;

namespace WinFormsNetCore
{
    class Foo<T> where T : Control
    {
        public static Control Create()
        {
            Control control = null;
            try
            {
                var controlType = typeof(T);
                if (typeof(T).IsSubclassOf(typeof(Control)))
                    control = Activator.CreateInstance(controlType) as Control;
                else
                    throw new InvalidOperationException("We need type parameter to be a Control");
            }
            catch (Exception ex)    // $BUG: Pokemon exception handling
            {
                control = null;
            }
            return control;
        }
    }


    class MainForm : Form
    {
        [STAThread]
        static void Main()
        {
            var x = Foo<TextBox>.Create();
            MessageBox.Show($"{x.GetType()}");
        }
    }
}
 
As well as this one. You just need to pay attention to the kind of object you are creating.
C#:
public static Foo<T> CreateFoo()
{
    Foo<T> control = null;
    try
    {
        var controlType = typeof(T);
        if (typeof(T).IsSubclassOf(typeof(Control)))
            control = Activator.CreateInstance(typeof(Foo<T>)) as Foo<T>;
        else
            throw new InvalidOperationException("We need type parameter to be a Control");
    }
    catch (Exception ex)    // $BUG: Pokemon exception handling
    {
        control = null;
    }
    return control;
}
 
Now, on the other hand what you are trying to do is:
C#:
class Base
{
}

class Foo : Base
{
}

class Wrapper<T> where T : Base
{
}

Wrapper<Foo> fooObject = new Wrapper<Foo>();
Wrapper<Base> baseObject = fooObject;

This will never work because the type Wrapper<Foo> is not the same type as Wrapper<Base>.
 

Latest posts

Back
Top Bottom