Search code examples
.netoopvirtualkeyword

What if I suppress "override"?


I remarked the compiler generates a warning if I suppress the override/new (Overloads/Shadows) keyword. Normally, I set the necessary keyword.

But what if i forget it?

// >>>> Case A - not virtual property -
class MyPoint : Point
{
    int X { get; set; } // vs new int X { get; set; }
}

// >>>> Case B - virtual property -
class Foo 
{ 
    virtual int Value { get { return 0; } }
}

class Bar : Foo
{ 
    // vs override/new int Value { get { return 1; } } 
    int Value { get { return 1; } }
}

Solution

  • Then you're not overriding the property, you're creating a new one, just as if you used the new keyword.

    Bar x = new Bar();
    Foo y = x;
    Console.WriteLine(x.Value); // Uses Bar.Value
    Console.WriteLine(y.Value); // Uses Foo.Value
    

    This is usually clearer when demonstrated with methods - in this case even when you override, you're still ending up with a separate backing fields in both classes, it's just that one of the fields will be redundant. Without overriding, you've got two backing fields, and which one you access via the property will depend on the compile-time type of the expression you're using to access it.