Справочник по объектам — C#


public class Student
{
    // Свойства, фактически это приватные поля
    private int age; 
    private string name;

    // Конструктор, принимающий параметры
    public Student(string name, int stAge)
    {
        this.name = name; // `this.` is required here
        age = stAge; // `this.` is not required here
    }

    // Конструктор без параметров
    // Это конструктор.
    public Student()
    {
        name = "no name";
        this.age = 0; // `this.` is not required here
    }

    // Метод, реализующий операцию копирования (конструктор копирования)
    // constructor overloading
    public Student(Student other)
    {
        name = other.name; 
        age = other.age; // `this.` is not required here
    }

    // Метод, возвращающий имя
    public string GetName()
    {
        return name;
    }

    // Метод, возвращающий возраст
    public int GetAge()
    {
        return age;
    }
}

public static void Main()
{
    // Создание массива студентов
    Student[] students = new Student[3];

    // Инициализация с использованием конструктора с параметрами
    students[0] = new Student("Dana", 17);

    // Инициализация с помощью пустого конструктора
    students[1] = new Student();

    // Инициализация с использованием конструктора копирования
    students[2] = new Student(students[0]);

    // Вызов внешней функции возвращает имя самого старшего ученика
    string oldestName = MaxAge(students);

    Point p1 = new Point(5, 3); // Инициализация точки
    Point p2 = new Point(2, 1);

    // Вызов внутреннего метода. Имя объекта, затем точка
    // В качестве параметра `p2` передается `p1`, и вызывается метод над объектом.
    Console.WriteLine($"Dist p1⟺p2 is: {p1.Distance(p2):0.00}");

}

Внешние операции

  /// <summary>
  /// Scans an array of students for the oldest.
  /// Assumes the array contains no nulls.
  /// </summary>
  public static Student MaxStdNoNulls3(Student[] students)
  {
    Student maxSt = students[0];
    foreach (Student st in students)
      if (st.GetAge() > maxSt.GetAge())
        maxSt = st;

    return maxSt;
  }

  /// <summary>
  /// Версия в одной строке, запрещенная для использования на экзаменах и выпускных экзаменах
  /// linq запрещено
  /// </summary>
  public static Student MaxStudent4(Student[] students)
    => students.MaxBy(st => st.GetAge());

  /// <summary>
  /// Внешняя функция, принимающая массив учеников и возвращающая имя самого старшего ученика
  /// + null checks
  /// </summary>
  public static string MaxStdName1(Student[] students)
  {
    Student maxSt = students[0];

    for (int i = 1; i < students.Length; i++)
    {
      // Проверка, что элемент массива не равен null
      if (students[i] != null)
      {
        // Также `maxSt` может быть `null`
        if (maxSt == null || students[i].GetAge() > maxSt.GetAge())
          maxSt = students[i];
      }
    }

    return maxSt.GetName(); // исключение NullReferenceException ⟵ если все элементы пусты
  }

  /// <summary>
  /// Scans an array of students for the oldest
  /// + null checks
  /// </summary>
  /// <param name="students">A non-null array, but can contain nulls</param>
  /// <returns>The student whose age is maximal</returns>
  public static Student MaxStudent2(Student[] students)
  {
    Student maxSt = null;

    foreach (Student st in students)
    {
      // Пропуск пустых ячеек
      if (st is not null &&
          (maxSt is null || st.GetAge() > maxSt.GetAge()))
        maxSt = st;
    }

    return maxSt;
  }