I'm debugging the following code:
class A
{
public virtual string X => "A";
}
class B : A
{
public bool OwnX { get; set; } = true;
public override string X
=> OwnX ? "B" : base.X; // (o)
}
class Program
{
static void Main() => Console.WriteLine(new B().X);
}
And I have a breakpoint on the line marked with (o). When the breakpoint hit, I'm trying to evaluate base.X and getting its value "B":
The question is: why not "A"?
As others have mentioned, this bug is well known.
You can trivially check that the actual value of base.X is A, it is just the Expression Evaluator that returns the wrong result:
Because X is not evaluated in runtime, it will also not evaluate in the debugger. So it assumes it is the same.
Because base.X is not actually called, it has never been evaluated as A. The overwriting property is because of that leading.
If you'd like to do so, make a constant out of it.
Maybe you should read a little bit more about this ?: Operator https://docs.microsoft.com/en-us/dotnet/articles/csharp/language-reference/operators/conditional-operator
Since default value OwnX is true.
Give it a try to this code:
B b = new B();
b.OwnX = false;
Console.WriteLine(b.X);
Explaining this code: public override string X => OwnX ? "B" : base.X;
to make it more readable:
public override string X
{
get {
if (Ownx == true) // this is the default value.
{
return "B";
}
else{
return "A";
}
}