0

Here I have the following code in which I have created two class A and B. Then in the main method, I created the object of both the class and assign child object to parent object. I don't understand how it works in c# can anyone explain me?

 class Program
{
    static void Main(string[] args)
    {
        A objA = new A();
        B objB = new B();
        objA = objB;


        Console.ReadLine();
    }

}

public class A
{
    public string ABC { get; set; }

    public string XYZ { get; set; }

    public string lmn { get; set; }


}

public class B : A
{
    private string vvmdn { get; set; }

    public string mkkk { get; set; }

}

enter image description here

Daniel Williams
  • 8,912
  • 15
  • 68
  • 107
Parth Savadiya
  • 1,203
  • 3
  • 18
  • 40
  • 5
    they are not "available", it's only the debugger that knows that the real type of the instance referenced by `objA` is still a `B` and therefor is able to show those properties, too. This is afaik done via reflection. – René Vogt Dec 20 '17 at 15:19
  • 1
    You can even see that in the first line of that tool tip it tells you the type `Console.Application.B`. – René Vogt Dec 20 '17 at 15:20
  • Covariance/contravariance - try [this answer](https://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example) – peeebeee Dec 20 '17 at 15:27
  • I think you are getting confused between program code and object at runtime. In program code `objA` is declared as `A`, but at runtime it is an instance of `B`. – DotNet Developer Dec 20 '17 at 17:56

1 Answers1

1

The reference objA points to a B object in memory and the debugger shows all properties of this object.

You can access non-public members of an object at runtime yourself using reflection: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection. This is basically what the debugger in Visual Studio does.

The type of the reference objA is indeed A but the actual object that it points to in memory is a B.

mm8
  • 163,881
  • 10
  • 57
  • 88