public abstract class SampleA
{
public abstract string PropertyA {get;set;}
}
How to Override abstract PropertyA ?
public abstract class SampleA
{
public abstract string PropertyA {get;set;}
}
How to Override abstract PropertyA ?
You are trying to override a property with a field
Properties provide access to a field by get
and set
value accessors. Please read this to better understand the difference. So because they are not the same, your IDE proposed you to hide the parent Property by using the new
-Keyword.
If you want to know why the
new
Keyword didn't work in your case, read this.
In your Question, it seems like PropertyA
in your code needs to be set on inherited classes, but can't be changed from outside. So maybe do it like this:
public abstract class SampleA
{
// no setter -> cant be changed after initialization
public abstract string PropertyA { get; }
// protected setter -> can only be changed from inside SampleA or Sample
public abstract string PropertyB { get; protected set; }
}
public class Sample : SampleA
{
public override string PropertyA { get; } = "override";
public override string PropertyB { get; protected set; } = "override";
}
Do it like this:
public class Sample : SampleA
{
public override string PropertyA { get; set; } = "override";
}
or even implement it with more behavior:
public class Sample : SampleA
{
private string _propertyA = "override";
public override string PropertyA
{
get { return _propertyA; }
set
{
// Maybe do some checks here
_propertyA = value;
}
}
}
When you override your property you should write both get
and set
. In your case you create a new property with the same name but with another signature.