C#의 Array.AsReadOnly(T[]) 메서드는 지정된 배열을 감싸는 읽기 전용 래퍼(Wrapper)를 반환합니다. 이때 반환되는 타입은 ReadOnlyCollection<T>로, 외부에서 컬렉션의 내용을 임의로 수정하는 것을 방지할 수 있습니다.
구문 (Syntax)
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
여기서 T는 배열에 저장된 요소의 타입을 의미하며, 매개변수 T[] array는 인덱스가 0부터 시작하는 1차원 배열입니다.
주요 특징
Array.AsReadOnly 메서드는 원본 배열 자체를 복사하지 않고 읽기 전용 뷰만 제공합니다. 따라서 원본 배열이 변경되면 읽기 전용 래퍼를 통해서도 변경된 내용이 그대로 반영됩니다. 반대로 래퍼를 통해 요소를 수정하려고 하면 NotSupportedException 예외가 발생합니다.
예제 (Example)
다음은 Array.AsReadOnly(T[]) 메서드를 실제로 구현한 예제입니다.
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
String[] arr = { "John", "Tom", "Katie", "Brad" };
// 읽기 전용 IList 래퍼 생성
IList<String> list = Array.AsReadOnly( arr );
// 읽기 전용 IList의 값 출력
Console.WriteLine( "초기 읽기 전용 IList..." );
display( list );
// 읽기 전용 래퍼를 변경 시도
try {
list[0] = "Kevin";
list[1] = "Bradley";
}
catch ( NotSupportedException e ) {
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message );
Console.WriteLine();
}
Console.WriteLine( "두 요소를 변경하려 했지만, 읽기 전용이므로 IList는 그대로 유지됩니다..." );
display( list );
}
public static void display( IList<String> list ) {
for ( int i = 0; i < list.Count; i++ ) {
Console.WriteLine(list[i] );
}
Console.WriteLine();
}
}출력 결과 (Output)
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
초기 읽기 전용 IList... John Tom Katie Brad System.NotSupportedException Collection is read-only. 두 요소를 변경하려 했지만, 읽기 전용이므로 IList는 그대로 유지됩니다... John Tom Katie Brad
정리
Array.AsReadOnly(T[]) 메서드는 배열 데이터를 외부에 노출하면서도 무분별한 수정을 막고 싶을 때 유용하게 사용됩니다. 읽기 전용 래퍼를 통해 컬렉션의 안정성을 보장할 수 있으며, 수정 시도가 있을 경우 NotSupportedException이 발생한다는 점을 기억해 두면 좋습니다.