A few days ago I have found out for myself about one more difference between PHP and C# OOP impelentations. Look at the following code snippet in PHP:
What do you expect it to show – ‘Parent’ or ‘Child’? The PHP manual says the result will be ‘Child’. And it seems quite logical to me as I would expect public property to be overridden.
Now rewrite the same code to C#:
Run the code and you will get ‘Parent’…
Change access modifier of
val to private in the parent class. Now both PHP and C# outputs the same – ‘Parent’. Why?
First thing to mention is that unlike PHP, public identifiers cannot be overridden in C#. Calling
this points to parent object and returns “not overridden” value of
val as a result. Private identifers inside parent are not accessible for the child and therefore are not overridden so everything becomes clear.
To make C# behavior similar to PHP you should either add a method with the same signature and with override keyword to Child class and mark parent method as virtual:
or use overridden public properties to access the
val value. This will work correctly as unlike public fields, public properties can be overridden.
I couln’t find any “standard” behaviour for this case. So I guess it was up to C# and PHP teams how to implement this.
Original post can be found here