WriteLine with a class

Console.WriteLine(t) perform implicit conversion of t to string. So you need to override ToString() for all your classes or create string from your class explicitly.

Example:

class School
    {
        public string name;
        List<Student> Students = new List<Student>();

        ...
        public override string ToString()
        {
           var stringValue = name;
           foreach(var student in Students)
           {
              stringValue += student.ToString();
           }
           return stringValue;
        }
    }

class Student
{
    public int Age;
    public string Name;
   ...
    public override string ToString()
    {
        return string.Format("{0} {1}", Name, Age);
    }

}

Leave a Comment