Reputation: 53
Class A :-
class classOne
{
public int intOne = 0;
public int Sub()
{
return 1;
}
public virtual int Add()
{
return 1;
}
}
Class Two:-
class classTwo:classOne
{
public new int Sub()
{
return 2;
}
public override int Add()
{
return 2;
}
}
Class Three
class classThree : classTwo
{
public int Sub()
{
return 3;
}
}
Program.cs
classOne obj = new classOne();
classThree obj3 = new classThree();
obj = obj3;
Console.WriteLine(obj.Sub());
Output is 1.
My doubt is I initialized a obj with classOne .Then I assigned the same object with ClassThree using new keyword classThree obj3 = new classThree();
. How does it call classOne.sub()
. How is this happening ? My understanding is, it supposed to call classThree.Sub() .
Upvotes: 0
Views: 57
Reputation: 62542
You haven't made Sub
virtual, so the compiler will use the static type of the variable to determine which instance to call. Since the static type of obj
is classOne
it will call classOne.Sub()
Upvotes: 1