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();
}
}