Home > Enterprise >  How to call a child class method C#
How to call a child class method C#

Time:12-05

I have a base class and a child class, in the latter there is a method that is not present in the base class. Having several child classes with different methods, I need to declare an array of the type of the base class, but this way I cannot call the methods of the child classes. Here's my code:

Base class

public class Athlete{
  protected string name;

  public Athlete(string n)
  {
    this.name=n;
  }
}

Child Class

public class Swimmer:Athlete{
   string team;

  public Swimmer(string n, string t):Base(string n)
  {
    this.team=t;
  }
  public string Swim()
  {
    return "I'm swimming!!!!" ;
  }
}

Program

  Athete test = New Swimmer("John","Tigers");
  Console.WriteLine(test.Swim()); //Error!!

How can I solve this? Thanks in advance to anyone that will help me.

CodePudding user response:

You're not setting the value of Athlete correctly. It shouldn't pass the type, only the value to initialise the base class. In addition, you're using Base (uppercase B), which in my experience is used to mark a constructor as the "base" constructor in the class, when you have more than on constructor in your class. To set the values of the parent object, you should use base(val) (lowercase)

Try changing the constructor signature of Swimmer to the following:

public Swimmer(string n, string t) : base(n)
{
    this.team = t;
}

This will correctly pass the value of n to the constructor of Athlete for you.

Full Code:

internal class Program
{
    static void Main(string[] arge)
    {
        Swimmer s = new Swimmer("Nick", "My Team");
        Console.WriteLine(s.Swim());
    }
}    

public class Athlete
{
    protected string name;

    public Athlete(string n)
    {
        this.name = n;
    }
}

public class Swimmer : Athlete
{
    string team;

    public Swimmer(string n, string t) : base(n)
    {
        this.team = t;
    }
    public string Swim()
    {
        return "I'm swimming!!!!";
    }
}

CodePudding user response:

//base class
public class Athlete
{
    protected string name;

    public Athlete(string n)
    {
        name = n;
    }
}
// child class
public class Swimmer : Athlete
{
    string team;

    public Swimmer(string n, string t) : base(n)
    {
        this.team = t;
    }

    public string Swim()
    {
        return "I'm swimming!!!!";
    }
}

//program main method
   Athlete test = new Swimmer("John", "Tigers");
            if (test is Swimmer) {
                var swimmer = test as Swimmer;
                Console.WriteLine(swimmer.Swim());
            }

CodePudding user response:

I found the solution:

//program
Console.WriteLine(((Swimmer)test).Swim());
  • Related