Pages

Saturday, October 3, 2009

Another PHP5 and C# OOP difference

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:

01.class ParentClass {
02.public $val = 'Parent';
03.
04.public function GetValue()
05.{
06.echo $this->val;
07.}
08.}
09.
10.class ChildClass extends ParentClass {
11.public $val = 'Child';
12.}
13.
14.$a = new ChildClass();
15.$a->GetValue();

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#:

01.class Parent {
02.public string val = "Parent";
03.
04.public void GetValue() {
05.Console.WriteLine(this.val);
06.}
07.}
08.
09.class Child:Parent {
10.public string val = "Child";
11.}
12.
13.Child child = new Child();
14.child.getValue();

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 GetValue(),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:

01.class Parent {
02.public string val = "Parent";
03.
04.public virtual void GetValue() {
05.Console.WriteLine(this.val);
06.}
07.}
08.
09.class Child:Parent {
10.public string val = "Child";
11.
12.public override void GetValue() {
13.Console.WriteLine(this.val);
14.}
15.}

or use overridden public properties to access the val value. This will work correctly as unlike public fields, public properties can be overridden.

01.class Parent {
02.private string privateVal = "Parent";
03.public virtual string val
04.{
05.get { return privateVal; }
06.}
07.
08.public void GetValue()
09.{
10.Console.WriteLine(this.val);
11.}
12.}
13.
14.class Child : Parent {
15.private string privateVal = "Child";
16.public override string val
17.{
18.get { return privateVal; }
19.}
20.}

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