Suppose I've following two class & their relationship as shown in below.
public class Parent
{
public int parentID { get; set; }
}
public class Child : Parent
{
public string childId { get; set; }
}
In the main method, while I'm creating a parent class object with a child class instance that time I can only access or see the parent class property as follows.
but in runtime, I can see the property from both classes is exists as follows.
I'm not getting the logic on the mentioned scenario. Please let me clear on this topic.
CodePudding user response:
This is not about the logic but rather Intellisense vs a debugger. pParent.
at design time and Intellisense acting against a variable declared as Parent
. But at runtime, the debugger looks inside actual object, which is Child
as per
Parent pParent = new Child();
And this assignment is legal because Child
derived from Parent
. But at design time you don't have a real object. So what do you do? - cast
Child castFromParent = (Child)pParent;
Console.WriteLine(castFromParent.childId); // <-- no design time issues
Basically, it comes down to Compilation vs runtime Polymorphism. 2 different things.
CodePudding user response:
The difference is that the compile time type of a reference and the runtime type of the object its pointing to can be two completely different things.
Obviously both types must be related (assignment compatibility) but the distinction is still there and its important you understand it:
object myString = "Hello";
the compile time type of the variable myString
is System.Object
. But when you run the code, the runtime type of the object stored in myString
is System.String
.
Intellisense can only reason about compile time types while the debugger can reason about the runtime type of objects.