C#의 인덱서(Indexer)를 사용하면 클래스를 배열처럼 편리하게 사용할 수 있습니다. 인덱서를 통해 내부 데이터에 접근하는 방법을 쉽게 구현할 수 있어 코드 가독성과 사용성을 높여줍니다.
1. 인덱서란?
인덱서는 클래스나 구조체가 배열처럼 인덱스를 받아 내부 데이터를 반환하거나 설정할 수 있게 하는 기능입니다. 보통 this 키워드를 이용해 정의합니다.
2. 간단한 인덱서 예제
class SampleCollection
{
private string[] data = new string[5];
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
위 예제처럼 this[int index]를 정의하면 SampleCollection 인스턴스를 배열처럼 사용할 수 있습니다.
3. 실용 예제: 학생 이름 관리
class StudentGroup
{
private string[] students = new string[10];
public string this[int index]
{
get
{
if(index < 0 || index >= students.Length)
throw new IndexOutOfRangeException();
return students[index];
}
set
{
if(index < 0 || index >= students.Length)
throw new IndexOutOfRangeException();
students[index] = value;
}
}
}
// 사용 예시
var group = new StudentGroup();
group[0] = "홍길동";
string name = group[0];
인덱서 구현 시 인덱스 검증을 추가해 안전하게 접근할 수 있도록 하였습니다.
'C#' 카테고리의 다른 글
| C# 메모리 누수 방지를 위한 약한 참조(WeakReference) 사용 (1) | 2026.04.20 |
|---|---|
| C# 이벤트 접근자(add/remove) 커스터마이징 (1) | 2026.04.20 |
| C# CancellationToken으로 작업 취소 구현하기 (0) | 2026.04.18 |
| C# Lock과 Monitor로 스레드 동기화 (0) | 2026.04.17 |
| C# 동적 타입(dynamic)과 DLR 이해하기 (0) | 2026.04.17 |