Home   Cover Cover Cover Cover
 

Initialisierung von Objekten und Collections

A05.cs
/* Initialization of objects and collections
   This example shows how to use object initializers and
   collection initializers.
------------------------------------------------------------*/
using System;
using System.Collections.Generic;

class Student {
  public string Name;
  public int Id;
  public string Field { get; set; }
  public Student() {}
  public Student(string name) { Name = name; }
}

public class A5 {
  
  public static void Main() {
    var students = new List< Student > {
      new Student { Name = "Bob Foster",   Id = 2008114, Field = "Computing" },
      new Student { Name = "Alice Miller", Id = 2008231, Field = "Mathematics" },
      new Student { Name = "Ann Malinsky", Id = 2008376, Field = "Computing" },
      new Student { Name = "John Dilbert", Id = 2008455, Field = "Chemistry" },
      new Student { Name = "Hugh Meyer",   Id = 2009004, Field = "Computing" },
      new Student { Name = "Robert Brown", Id = 2009057, Field = "Chemistry" },
      new Student { Name = "Jill Dawkins", Id = 2009196, Field = "Computing" },
      new Student { Name = "Susan Smith",  Id = 2009275, Field = "Mathematics" },
    };
    foreach (Student s in students) {
      Console.WriteLine(s.Name + " (" + s.Id + "), " + s.Field);
    }
  }
}