Accessing derived class property members from base class object in CSharp

I am having trouble accessing property members of derived class using base class object.

Scenario:

public class BaseClass{
    public virtual Write(BaseClass data){
    }
}

public class DerivedClass : BaseClass{

    private string name:

    public string Name {get {return name} set {name = value;} }

    public override Write(BaseClass data){
     Console.println(data.Name);  // gives me error here
    }

}

Answers


The reason you have a problem accessing properties in derived classes is that the base class does not (and more importantly should not) know anything about them. Different derived classes could have a different set of added properties. Making the base class aware of this would counteract important principles of object oriented design. One such principle that comes to mind is the Liskov Substitution Principle.


As stated, name does not exists in the BaseClass.

Either move "name" to the base class or create a separate Write Method that writes the inherited class's specific data.

public class DerivedClass : BaseClass{

    public string Name { get; set; }

    public override void Write(DerivedClass data) {
        Console.printLn(data.Name);
        base.Write(data)
    }

    // why print a different instance, just write self
    public void Write() {
        Console.printLn(this.Name);
        base.Write(this)
    }

}

Not sure why the Class would accept a different Class Instance to write when you can just invoke write on itself. Change the BaseClass signture to

public virtual Write()

or like WebControls

public virtual Write(HtmlTextWriter writer);

if you want simply debugging, you could just serialize to JSON or XML and then output that to your console


Need Your Help

net::ERR_CONNECTION_RESET PushStreamContent

connection-reset pushstreamcontent

I´m trying to stream a video using PushStreamContent, but some seconds after the video starts playing the browser gives me a net::ERR_CONNECTION_RESET ( Error )

Create nested JSON array

javascript arrays angularjs json slim

I'm trying to create a JSON array to send it to my web service. This is how my json should look like: