Denis Allan
Denis Allan

Reputation: 21

Calling a child class' method

I am attempting to use a list which contains a series of strings using this method

    public  List<String> ListJobs(Job job)
    {
        List<String> ListJobs = new List<string>();

        foreach (Job curjob in Jobs)
        {


            String jobAsString = curjob.ToString();

            ListJobs.Add(jobAsString); 

        }
        return ListJobs;
  //Get the list of strings  

My current structure is that of

JobLedger (The List in which it is all contained)

then the Job Parent class which is inherited by Visit and Pickup The problem is that in the above code, instead of using the overrided tostring method in the child class, it defaults to the parent class instead.

    public void NewerList()
        //No Pickup display problem is here. Liststring refers to base sting method instead of child
    {


        LstJob.Items.Clear();
        //Clears the list


        List<String> listOfVis = TheLedger.ListJobs(Thejob);
        //Get a list of strings to display in the list box


        LstJob.Items.AddRange(listOfVis.ToArray());


    }

I seem to have narrowed it down to This piece of code ehre, the List calls the parent Job Class, as opposed to either of the child classes

Upvotes: 0

Views: 178

Answers (3)

Dave
Dave

Reputation: 127

Try type casting the object you are getting to the class which contains the function you want to be used.

Upvotes: 1

sarwar026
sarwar026

Reputation: 3821

You need to use override before the overrided method.

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

Make sure you really override ToString.

What you are describing sounds more like you are shadowing it in the derived classes.

override (What you want):

public override string ToString()
{
    // ...
}

shadow (What I think you have):

public string ToString()
{
    // ...
}

// or:

public new string ToString()
{
    // ...
}

Upvotes: 0

Related Questions