qingsong
qingsong

Reputation: 785

How to override the type of a member in abstract class in child class

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?

Upvotes: 1

Views: 756

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500983

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>.

Upvotes: 6

Related Questions