C#에서 StringDictionary는 키와 값이 모두 문자열(string)로만 이루어진 컬렉션입니다. 일반 Hashtable과 달리 타입 변환이 필요 없어 문자열 데이터를 다룰 때 편리하며, System.Collections.Specialized 네임스페이스에 포함되어 있습니다.
StringDictionary에 새로운 키와 값을 추가하려면 Add() 메서드를 사용합니다. 아래 예제를 통해 살펴보겠습니다.
예제 1 – 기본 사용법
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary strDict = new StringDictionary();
strDict.Add("A", "John");
strDict.Add("B", "Andy");
strDict.Add("C", "Tim");
strDict.Add("D", "Ryan");
strDict.Add("E", "Kevin");
strDict.Add("F", "Katie");
strDict.Add("G", "Brad");
Console.WriteLine("StringDictionary 요소 출력...");
foreach(DictionaryEntry de in strDict) {
Console.WriteLine(de.Key + " " + de.Value);
}
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
StringDictionary 요소 출력... a John b Andy c Tim d Ryan e Kevin f Katie g Brad
주목할 점: 키는 소문자로 저장됩니다
출력 결과를 보면 원래 대문자로 추가한 키 "A", "B"가 소문자 "a", "b"로 변경되어 있는 것을 확인할 수 있습니다. 이는 StringDictionary가 내부적으로 키를 대소문자를 구분하지 않는(case-insensitive) 방식으로 처리하기 때문입니다. 따라서 "A"와 "a"는 동일한 키로 취급됩니다.
예제 2 – 숫자 형태의 키 사용
키는 반드시 알파벳일 필요는 없습니다. 숫자 형태의 문자열도 키로 사용할 수 있습니다.
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringDictionary strDict = new StringDictionary();
strDict.Add("1", "Electric Cars");
strDict.Add("2", "SUV");
strDict.Add("3", "AUV");
Console.WriteLine("StringDictionary 요소 출력...");
foreach(DictionaryEntry de in strDict) {
Console.WriteLine(de.Key + " " + de.Value);
}
}
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
StringDictionary 요소 출력... 1 Electric Cars 2 SUV 3 AUV
Add() 메서드 사용 시 주의사항
- 중복 키 금지: 이미 존재하는 키를 Add()로 추가하려 하면
ArgumentException이 발생합니다. 기존 값을 수정하려면 인덱서(strDict["key"] = value;)를 사용해야 합니다. - null 값 허용 여부: null 키나 null 값은 허용되지 않으므로, 추가 전에 유효성 검사를 하는 것이 안전합니다.
- foreach 순회: DictionaryEntry 타입으로 요소를 순회하며 Key와 Value 속성에 각각 접근할 수 있습니다.
이처럼 StringDictionary의 Add() 메서드는 문자열 기반의 키-값 쌍을 간단하게 관리할 수 있게 해주며, 설정값 저장이나 간단한 매핑 작업에 유용하게 활용할 수 있습니다.