Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# complex inheritance

Tags:

c#

inheritance

Suppose we have code like this:

interface I
{
    int P { get; }
}

class A : I
{
    public virtual int P { get { return 0; } }
}

class B : A
{
    public override int P { get { return 1; } }
}

class C : B, I
{
    public int P { get { return 2; } }
}

A c = new C();
I ic = new C();

Now the question is what whould be c.P and ic.P? Actually I know it will be 1 and 2, but can you explain me why?

like image 237
Stas Yarkin Avatar asked Dec 01 '22 03:12

Stas Yarkin


2 Answers

In the case of A c = new C();, it's going to call the first function it finds that correctly overrides the function declared in A. Since C.P doesn't override it, but hides it, the virtual tree traversal (polymorphic resolution) won't call the C.P function, it'll instead call the lowest one in the inheritance tree, which is B.P.

In the case of I ic = new C();, it will happily call the direct interface implementation of P, since it's not concerned with a polymorphic virtual call, so in that case it calls C.P.

Note: it's key here that C has I directly in its inheritance declaration (i.e. looks like class C : B, I instead of class C : B) for this behavior. If it did not, the ic.P call would again refer to the overridden inherited P just like c.P, and would also return 1.

You should see a warning that says the following, which helps give you a clue that something isn't done quite right:

'C.P' hides inherited member 'B.P'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

like image 188
Gjeltema Avatar answered Dec 04 '22 12:12

Gjeltema


class B : A means that class B inherits class A , in simple words means that class B will have all the properties-functions that class A has. BUT when you say public override int P , (the "key word" is override) means that for 'P' class B will behave in a different way. It's like "hiding" the class A for 'P'.

More useful is to read documentation:

Inheritance

like image 32
Emmanouil Chountasis Avatar answered Dec 04 '22 14:12

Emmanouil Chountasis