클래스 정의는 class 라는 C# 키워드를 사용해서 정의한다. class 키워드 뒤에 클래스명을 써 주고, 클래스 블럭 안에 필드, 메서드, 속성, 이벤트 등을 정의해 준다.
클래스 각 멤버들은 public, protected, private 등의
접근제한자(Access Modifier)에 따라 외부 객체로부터 접근이 허용될 수도 있고 제한될 수도 있다.
예제
public class MyCustomer
{
// 필드
private string name;
private int age;
// 이벤트
public event EventHandler NameChanged;
// 생성자 (Constructor)
public MyCustomer()
{
name = string.Empty;
age = -1;
}
// 속성
public string Name
{
get { return this.name; }
set
{
if (this.name != value)
{
this.name = value;
if (NameChanged != null)
{
NameChanged(this, EventArgs.Empty);
}
}
}
}
public int Age
{
get { return this.age; }
set { this.age = value; }
}
// 메서드
public string GetCustomerData()
{
string data = string.Format("Name: {0} (Age: {1})",
this.Name, this.Age);
return data;
}
}