0

I am just startint to experiment with base classes that accept a generic variable Type.

Sample Classes:

public class BaseClass<T> : where T : new() { }

public class ChildClassA : BaseClass<A> { }

public class ChildClassB : BaseClass<B> { }

public class A { }

public class B { }

I know I can instantiate like this: BaseClass<A> a = new ChildClassA() & BaseClass<B> b = new ChildClassB(). However, I am trying to find a common base class that I can use to instantiate any children of BaseClass without knowing the type of .

I tried something like BaseClass<object> a = new ChildClassA(), but I get the following error message:

Cannot implicitly convert type 'A' to type 'object'

Is there some other common base class I can use or am I prevented from doing this completely in c#?

Update 1 I have a WinUI project that has many ViewModels that use BaseClass to implement shared add, edit, record navigation methods. I was trying to pass those viewmodels through to a UserControl so that I could Bind the Click event on Toolbar back to the ViewModel methods without having to pass through the same 10 functions every time I want to implement the Toolbar in XAML.

Toolbar UserControl

public sealed partial class Toolbar : UserControl
{
    public ViewModelBase_Toolbar<object> ViewModel
    {
        get => (ViewModelBase_Toolbar<object>)GetValue(ViewModelProperty);
        set => SetValue(ViewModelProperty, value);
    }
    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(ViewModelBase_Toolbar<object>), typeof(Toolbar), new PropertyMetadata(null));

    public Toolbar()
    {
        this.InitializeComponent();
            
    }
}
  • I mean, you could make a non generic interface containing the methods you need first, and then a base class that defines the methods with new – Icepickle Nov 01 '22 at 18:23
  • @Icepickle My goal is to still be able to access the common functionality of the methods in base and then implement some additional code that only applies to the subclass. My problem is that I can't pass my ViewModel through to the UserControl as it is currently set up. – Bloody Solomon Nov 01 '22 at 18:35

1 Answers1

0

You cannot do that in C#.

What/why are you trying to do this, and perhaps we can find a workaround.

James Curran
  • 101,701
  • 37
  • 181
  • 258