3. Класове
public class Person {
private string name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void show() {
Console.WriteLine(name + “ ” + age);
}
public void showAgeGroup() {
if (age<14) Console.WriteLine(name + “is a child”);
else if (age<18) Console.WriteLine(name + “is an adolescent”);
else Console.WriteLine(name + “is an adult”);
}
}
4. Създаване и използване на обекти от
клас
Person person1 = new Person(“John”, 15);
person1.show();
person1.showAgeGroup();
5. Наследяване на класове
public class Employee : Person {
private int salary;
public Employee(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public void showSalaryGroup() {
if (salary<1000) Console.WriteLine(name + “’s salary is below average”);
else Console.WriteLine(name + “’s salary is above average”);
}
}
6. Композиция на класове
public class Company {
private string name;
private List<Employee> employees;
public Company(String name) {
this.name = name;
employees = new List<Employee>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void showEmployees() {
Console.WriteLine(name + “has the following employees”);
foreach (Employee employee in employees) employee.show();
}
}
7. Изключения
public Person(String name, int age) {
if (age<0) throw new ArgumentException(“Age must be non negative”);
this.name = name;
this.age = age;
}
8. namespace
Групира код със сходна функционалност
namespace SampleNamespace
{
class SampleClass { }
interface SampleInterface { }
struct SampleStruct { }
enum SampleEnum { a, b }
delegate void SampleDelegate(int i);
namespace SampleNamespace.Nested
{
class SampleClass2 { }
}
}