Question

I am not able to access simple field from derived class so what is use of polymorphism in case of fields. If I have to downcast to ResponseMBP to get the Name property then my client needs to know about derived class.

So does polymorphism work only for methods?

public abstract class Response
{
}

public class ResponseMbp : Response
{        
    public string Name = "My Name";        
}

class Program
{
    static void Main(string[] args)
    {
        Response r = new ResponseMbp();
        Console.Write(r.Name);
    }
}
Was it helpful?

Solution

First of all for field polymorphism, you should have that field declared in both the base and derived class (as is the case with method polymorphism).

Now in you example, the field "name" is only part of derived class signature, and you do not have "name" variable in the signature of your base class. Due to this the object of your base class, though it is instantiated with derived class, would only show you base class signature items. Thus due to this reason, you are not able to use r.name in your example.

To know proper usage of field polymorphism, refer this link.

OTHER TIPS

You are defining your variable as type Response. At this point you can only access properties and variables that are contained in the Response class and its superclasses.

You're also trying to refer to Name while the property is named name.

ResponseMbp is inheriting from Response. So ResponseMbp is a Response, but a Response is not a ResponseMbp.

Since you are defining the property Name in ResponseMbp, Response does not know, or care, about it.

If you defined Name in Response, ResponseMbp would inherit the property, and it would be accessible from either class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top