Reputation: 210
Here is an Inheritance question. I was trying to understand TAG1 to TAG3 Process. what exactly going happen and hold which class reference. Looking forward to your suggestion.
static void Main(string[] args)
{
B b = new B(); **// What Happens here TAG1**
A a = b; **//What Happens here TAG2**
B x = new A() as B; **//what happens here TAG3**
a.F();
a.G();
a.H();
a.Z();
b.F();
b.G();
b.H();
b.Z();
x.F();
Console.ReadLine();
}
public class A
{
public void F() { Console.WriteLine("A.F"); }
public virtual void G() { Console.WriteLine("A.G"); }
public virtual void H() { Console.WriteLine("A.H"); }
public void Z() { Console.WriteLine("A.Z"); }
}
public class B : A
{
new public void F() { Console.WriteLine("B.F"); }
public override void G() { Console.WriteLine("B.G"); }
new public void H() { Console.WriteLine("B.H"); }
}
Upvotes: 1
Views: 46
Reputation: 16328
B b = new B(); **// What Happens here TAG1**
An instance of B is created here, and b
holds a reference to it.
A a = b; **//What Happens here TAG2**
a
is assigned that b
instance, which means you can access the A
part of the previously crated B
object.
B x = new A() as B; **//what happens here TAG3**
You create an A
object and cast it to B
, but the cast is gonna fail and return null
. Therefore x
will not reference the instance of an object.
Upvotes: 2