Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 배열이 읽기 전용(Read-Only)인지 확인하는 방법


C#에서 배열이 읽기 전용(read-only) 상태인지 확인하려면 IsReadOnly 속성을 활용하면 됩니다. 이 속성은 배열이 읽기 전용일 경우 true, 쓰기가 가능한 경우 false를 반환합니다.

예제 1: 빈 배열 확인하기

다음 코드는 빈 문자열 배열을 생성한 뒤, 고정 크기 여부와 읽기 전용 여부를 함께 출력하는 예제입니다.

using System;
public class Demo {
    public static void Main(){
        string[] products = new string[] { };
        Console.WriteLine("One or more products begin with 'E'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("E")));
        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
    }
}

출력 결과

One or more products begin with 'E'? = False
Is the array having fixed size? = True
Is the array read only? = False

실행 결과에서 알 수 있듯이, 일반적인 배열은 기본적으로 고정 크기(IsFixedSize = True)이지만 읽기 전용(IsReadOnly)은 아닙니다. 즉, 배열 요소의 값을 자유롭게 변경할 수 있습니다.

예제 2: 값이 있는 배열 확인하기

이번에는 실제 데이터가 담긴 배열을 대상으로 확인해 보겠습니다. Array.Exists() 메서드를 사용하면 특정 조건에 맞는 요소가 하나라도 존재하는지 검사할 수 있습니다.

using System;
public class Demo {
    public static void Main(){
        string[] products = { "Mobiles", "Laptop", "Watches", "Books" };
        Console.WriteLine("Products list...");
        foreach(string s in products){
            Console.WriteLine(s);
        }
        Console.WriteLine("\nOne or more products begin with the letter 'C'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("C")));
        Console.WriteLine("One or more products begin with the letter 'D'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("D")));
        Console.WriteLine("One or more products begin with the letter 'T'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("T")));
        Console.WriteLine("One or more products begin with the letter 'E'? = {0}",
            Array.Exists(products, ele => ele.StartsWith("E")));
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
    }
}

출력 결과

Products list...
Mobiles
Laptop
Watches
Books
One or more products begin with the letter 'C'? = False
One or more products begin with the letter 'D'? = False
One or more products begin with the letter 'T'? = False
One or more products begin with the letter 'E'? = False
Is the array read only? = False

핵심 정리

  • IsReadOnly: 배열이 읽기 전용인지 여부를 나타내는 부울(Boolean) 속성입니다. 일반 배열은 항상 false를 반환합니다.
  • IsFixedSize: 배열은 선언 시점에 크기가 고정되므로 항상 true를 반환합니다.
  • Array.Exists(): 지정한 조건자(predicate)와 일치하는 요소가 하나라도 있으면 true를 반환합니다.

만약 진정한 의미의 읽기 전용 컬렉션이 필요하다면 Array.AsReadOnly() 메서드로 ReadOnlyCollection<T>를 생성하거나, 변경 불가능한(immutable) 컬렉션 타입을 사용하는 것이 좋습니다.