static void UsePersonCollection() { Console.WriteLine("***** Custom Person Collection *****\n"); PersonCollection myPeople = new PersonCollection(); myPeople.AddPerson(new Person("Homer", "Simpson", 40)); myPeople.AddPerson(new Person("Marge", "Simpson", 38)); myPeople.AddPerson(new Person("Lisa", "Simpson", 9)); myPeople.AddPerson(new Person("Bart", "Simpson", 7)); myPeople.AddPerson(new Person("Maggie", "Simpson", 2)); foreach (Person p in myPeople) { Console.WriteLine(p); } }
static void UsePersonCollection() { Console.WriteLine("***** Custom Person Collection *****\n"); PersonCollection myPeople = new PersonCollection(); myPeople.AddPerson(new Person("Homer", "Simpson", 40)); myPeople.AddPerson(new Person("Marge", "Simpson", 38)); myPeople.AddPerson(new Person("Lisa", "Simpson", 9)); myPeople.AddPerson(new Person("Bart", "Simpson", 7)); myPeople.AddPerson(new Person("Maggie", "Simpson", 2)); // This would be a compile-time error! // myPeople.AddPerson(new Car()); foreach (Person p in myPeople) Console.WriteLine(p); }
static void UserPersonCollection() { Console.WriteLine("***** Custom Person Collection *****\n"); PersonCollection myPeople = new PersonCollection(); myPeople.AddPerson(new Person(40, "Homer", "Simpson")); myPeople.AddPerson(new Person(38, "Marge", "Simpson")); myPeople.AddPerson(new Person(9, "Lisa", "Simpson")); myPeople.AddPerson(new Person(7, "Bart", "Simpson")); myPeople.AddPerson(new Person(2, "Maggie", "Simpson")); //myPeople.AddPerson("Firstname Lastname"); foreach (Person p in myPeople) { Console.WriteLine(p); } }
private static void UsePersonCollection() { Console.WriteLine("****** Custom Person Collection ******\n"); PersonCollection myPeople = new PersonCollection(); myPeople.AddPerson(new Person("Homer", "Simpson", 40)); myPeople.AddPerson(new Person("Marge", "Simpson", 38)); myPeople.AddPerson(new Person("Lisa", "Simpson", 9)); myPeople.AddPerson(new Person("Bart", "Simpson", 7)); myPeople.AddPerson(new Person("Maggie", "Simpson", 2)); // This would be a compile-time error! // myPeople.AddPerson(new Car()); foreach (Person p in myPeople) { Console.WriteLine(p); } Console.WriteLine(); }
static void UsePersonCollection() { PersonCollection myPeople = new PersonCollection(); myPeople.AddPerson(new Person("Homer")); myPeople.AddPerson(new Person("Mary")); myPeople.AddPerson(new Person("Lisa")); myPeople.AddPerson(new Person("Bart")); myPeople.AddPerson(new Person("Maggie")); //myPeople.AddPerson(new OperatingSystem(PlatformID.MacOSX, new Version(10, 0))); ERROR foreach (Person p in myPeople) { //Works without casting here Console.WriteLine(p); } try { foreach (int p in myPeople) { //Runtime error // Console.WriteLine(p); } } catch (InvalidCastException ex) { Console.WriteLine(ex.Message); } Console.WriteLine(); }