user8535817
user8535817

Reputation:

creating a base class type variable with the reference to an object with the type of an inheriting class

class Program
{
    static void Main(string[] args)
    {
        BaseC instance = new DerivedC();
        // I don't see Y here.
        Console.ReadLine();
    }
}

public class BaseC
{
    public int x;
}
public class DerivedC : BaseC
{
    public int y;
}

I'm talking about the first line in the Main function. When I create it like this: DerivedC instance = new DerivedC(); everything's clear for me, and I see both variables, but why don't I see Y when creating an object that way above? How does the type of the 'instance' variable (either BaseC or DerivedC) affect the result?

Upvotes: 0

Views: 107

Answers (2)

Habeeb
Habeeb

Reputation: 8007

Because the type of instance is BaseC, it will not expose Property y. To access Property y, you will need to do like below:

((DerivedC)instance).y

y is an extended property which is accessible only from the Child Class. That is the concept of Inheritence. The Child inherits the properties on child, not the other way round.

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37940

That's the way polymorphism works in C#: in a variable of a base class type, you are allowed to store a reference to an instance of any subclass - but if you choose to do that, you can only "see" the base class members through the variable. The reason for this is safety: it is guaranteed that no matter what the variable refers to, it will have an x. However, there might exist other subclasses that do not have a y.

You might argue that it's obvious that the variable refers to an DerivedC, but that's just because this is a simple example. Imagine some code where there is a function that takes a BaseC as a parameter. The function might be called in one place with a DerivedC, and in another place with a DifferentDerivedC that doesn't have a y. Then, the function would fail in the second call if it were allowed to access y.

Upvotes: 1

Related Questions