C#에서 Hashtable이 고정 크기(fixed size)를 가지고 있는지 확인하려면 IsFixedSize 속성을 사용하면 됩니다. 이 속성은 Hashtable의 크기가 고정되어 있으면 True, 요소를 자유롭게 추가하거나 삭제할 수 있으면 False를 반환합니다.
예제 1
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable(10);
hash.Add("1", "A");
hash.Add("2", "B");
hash.Add("3", "C");
hash.Add("4", "D");
hash.Add("5", "E");
hash.Add("6", "F");
hash.Add("7", "G");
hash.Add("8", "H");
hash.Add("9", "I");
hash.Add("10", "J");
Console.WriteLine("Hashtable이 고정 크기를 가지고 있습니까? = " + hash.IsFixedSize);
}
}출력
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Hashtable이 고정 크기를 가지고 있습니까? = False
예제 2
이번에는 Hashtable에 저장된 키-값 쌍을 함께 출력하고 고정 크기 여부를 확인하는 예제를 살펴보겠습니다.
using System;
using System.Collections;
public class Demo {
public static void Main(){
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", "");
hash.Add("Five", "Harry");
hash.Add("Six", "F");
hash.Add("Seven", "Tom");
hash.Add("Eight", "Andy");
hash.Add("Nine", "I");
hash.Add("Ten", "Tim");
Console.WriteLine("Hashtable의 키와 값 쌍...");
foreach(DictionaryEntry entry in hash){
Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
}
Console.WriteLine("Hashtable이 고정 크기를 가지고 있습니까? = " + hash.IsFixedSize);
}
}출력
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Hashtable의 키와 값 쌍... One : Katie Ten : Tim Five : Harry Three : Barry Seven : Tom Two : John Four : Eight : Andy Nine : I Six : F Hashtable이 고정 크기를 가지고 있습니까? = False
핵심 정리
IsFixedSize 속성은 ICollection 인터페이스에서 제공하는 속성으로, 컬렉션의 크기가 고정되어 있으면 True를 반환합니다. 일반적으로 new Hashtable()로 생성한 Hashtable은 요소를 동적으로 추가하거나 제거할 수 있으므로 항상 False를 반환합니다. 반면 Hashtable.ReadOnly() 또는 Hashtable.FixedSize() 메서드로 생성한 읽기 전용·고정 크기 래퍼의 경우에는 True가 반환됩니다.