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.
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();
}
}
}
namespace Task3
{
public abstract class Person
{
protected string _name;
public Person(){}
public Person(string name)
{
_name = name;
}
public abstract void PrintDetails();
}
}
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);
}
}
}
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");
}
}
}
Your PrintDetails()
method is printing the array without any kind of formatting (hence it's just printing the array type)
use string.Join
to print the array delimenated by commas
public override void PrintDetails()
{
Console.WriteLine("Hi my name is " + _name + " and I am studying " + string.Join(",", _subjects));
}
ought to do it.