I'm having trouble with inheritance/polymorphism in C#/Xamarin.Forms. There's multiple things I'd think I would be allowed to do, but I'm not, and from what I gather it seems I'm not inheriting correctly, so first things first:
Declarations
public abstract partial class CommonCell : ContentView, ICellSection
{
public static readonly BindableProperty TitleProperty = BindableProperty.Create("Title", typeof(string), typeof(CommonCell), default(string));
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public CommonCell()
: base()
{
}
public virtual IInputType GetInputType()
{
throw new NotImplementedException();
}
}
In the same file i also declare this derived class:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CellSection<T>: CommonCell where T : View, IInputType
{
private T _inputType;
public T InputType
{
get { return _inputType; }
set { _inputType = value; } //plus more stuff here
}
public CellSection ()
:base()
{
//Layout Initialization
}
public override IInputType GetInputType() //I get an error here (Problem 2)
{
return InputType;
}
}
I've only included one property and one method to demonstrate my problem, but there are many more declared the same way...
Problem 1
What happens is that when I create a new CellSection, like this:
CellSection<TextInput> section1 = new CellSection<TextInput>();
section1.Title = "New Title"; //This line is not allowed
I'm not allowed to access the Title property...
Error message: CellSection<TextInput>' does not contain a definition for 'Title'
I've been able to access it by adding the following code to the CellSection<T> class:
public string Title
{
get { return base.Title; }
set { base.Title = value; }
}
but this seems so damn unnecessary and redundant... There must be another way...
Problem 2
The other problem I have is that I'm not allowed to override the virtual method GetInputType(), it is in the code above as well, but this is the line I'm talking about:
public override IInputType GetInputType()
{
return InputType;
}
Error message: 'CellSection<T>.GetInputType()': no suitable method found to override
Problem 3
The final problem is that when I'm, from a different class/file, attempt to reference/cast a CellSection<T> to ICellSection (which is implemented by the base class CommonCell)
List<ICellSection> Sections = new List<ICellSection> { section1, section2 };
I get an error that it's not allowed.
Error message: Argument 1: cannot convert from 'CellSection<TextInput>' to 'ICellSection'
This one I'm more unsure about as I don't know if it's even possible (can't find examples on it), but the problem 1 and 2 I just don't understand why won't work as they seem pretty straight forward...