How to override the type of a member in abstract class in child class
-
18-09-2019 - |
Question
I have following code:
public abstract class TestProperty
{
public abstract Object PropertyValue { get; set; }
}
public class StringProperty: TestProperty
{
public override string PropertyValue {get;set}
}
which generate compilation error, I wonder should I have to use generic type in TestProperty in order to achive my goal of having different type of the same name in the child class?
Solution
Yes, C# doesn't support covariant return types. You can indeed use generics here:
public abstract class TestProperty<T>
{
public abstract T PropertyValue { get; set; }
}
public class StringProperty : TestProperty<string>
{
}
There's no need to override at this point - and indeed unless you're going to do anything else, you might as well get rid of StringProperty
entirely and just use TestProperty<string>
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow