1

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"); } } 

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please give more description on Tag2 and Tag3. Thanks.
for TAG3, it is almost equivalent to B x = (B)new A(); But when conversion failed, "as" keyword will return null (while conversion throws exception). msdn.microsoft.com/en-us/library/vstudio/cscsdfbt.aspx

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.