I am trying to print from an array in an exercise using inheritance and polymorphism...etc
The exercise is a student and teacher class that inherit from a Person class but display different results by overriding the the print method in both classes. The teacher class prints from string variables but the student class prints from a string variable and an array of strings. I was able to print everything but the part where i print the Array of string i get System.String[] which i understand as it's printing the name of the object instead of the value. I tried overriding the To.String method to pass it the printDetails method but since my printDetails method has a return type void, i can't do that.
Below is my code for reference:
Program.cs :
namespace Task3
{
class Program
{
static void Main(string[] args)
{
var people = new List<Person>();
string[] subjects = { "Math", "Science", "English" };
string studentName = "Sue";
Student student = new Student(studentName, subjects);
people.Add(student);
string faculty = "Computer Science";
string teacherName = "Tim";
Teacher teacher = new Teacher(teacherName, faculty);
people.Add(teacher);
foreach (var element in people)
{
element.PrintDetails();
}
Console.ReadKey();
}
}
}
Person.cs :
namespace Task3
{
public abstract class Person
{
protected string _name;
public Person(){}
public Person(string name)
{
_name = name;
}
public abstract void PrintDetails();
}
}
Student.cs :
namespace Task3
{
public class Student : Person
{
private string[] _subjects;
public Student(string name, string[] subjects) : base(name)
{
_subjects = subjects;
}
public override void PrintDetails()
{
Console.WriteLine("Hi my name is " + _name + " and I am studying " + _subjects);
}
}
}
Teacher.cs :
namespace Task3
{
public class Teacher : Person
{
private string _faculty;
public Teacher(string name, string faculty) : base(name)
{
_faculty = faculty;
}
public override void PrintDetails()
{
Console.WriteLine($"Hi my name is {_name} and I teach in the {_faculty} faculty");
}
}
}