Could someone please explain what the difference is between these two examples?
Class A
protected virtual string GetData()Class B
private override string GetData()
And the following:
Class A
protected string GetData()Class B
private string GetData()
Assuming that ‘Class B’ inherits from ‘Class A’.
I always assumed that you need to use virtual in the superclass and override in the subclass if you want overriding of a method, however I tried removing the keywords and the program compiled fine. What exactly is the difference, if any?
The second example that you showed hides the GetData of the parent, it doesn’t override it.
Example:
It outputs:
Actually this sample is invalid, because it should use the
newkeyword inpublic new void Test2()in the Derived class.It works just like operator overloading. It doesn’t actually override anything. When you have the exact type
Derivedit calls the new method.You have to be really careful with hiding members, it is nothing like overriding (classes) or implementing (interfaces) at all. Only when you have the exact type it’ll call a
newmethod, otherwise it’ll still call the base type’s method!