C#에서 두 StringCollection 개체가 동일한지 확인하려면 Equals() 메서드를 사용합니다. 다만 한 가지 중요한 점이 있습니다. StringCollection은 Equals()를 재정의(override)하지 않기 때문에, 이 메서드는 컬렉션의 내용이 아닌 참조 동일성, 즉 두 변수가 같은 개체 인스턴스를 가리키는지를 비교합니다. 따라서 담고 있는 문자열이 완전히 같더라도 서로 다른 개체라면 결과는 False가 됩니다.
예제 1: 내용이 같은 두 컬렉션 비교하기
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol1 = new StringCollection();
strCol1.Add("Accessories");
strCol1.Add("Books");
strCol1.Add("Electronics");
Console.WriteLine("StringCollection1 요소...");
foreach (string res in strCol1) {
Console.WriteLine(res);
}
StringCollection strCol2 = new StringCollection();
strCol2.Add("Accessories");
strCol2.Add("Books");
strCol2.Add("Electronics");
Console.WriteLine("StringCollection2 요소...");
foreach (string res in strCol2) {
Console.WriteLine(res);
}
Console.WriteLine("두 StringCollection이 같은가? = " + strCol1.Equals(strCol2));
}
}실행 결과
StringCollection1 요소... Accessories Books Electronics StringCollection2 요소... Accessories Books Electronics 두 StringCollection이 같은가? = False
출력을 보면 두 컬렉션에 들어 있는 문자열은 완전히 동일하지만 결과는 False입니다. 그 이유는 strCol1과 strCol2가 각각 new 키워드로 생성된 서로 다른 개체이기 때문입니다.
예제 2: 같은 개체를 참조하는 경우 비교하기
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol1 = new StringCollection();
strCol1.Add("Accessories");
strCol1.Add("Books");
strCol1.Add("Electronics");
Console.WriteLine("StringCollection1 요소...");
foreach (string res in strCol1) {
Console.WriteLine(res);
}
StringCollection strCol2 = new StringCollection();
strCol2.Add("Accessories");
strCol2.Add("Books");
strCol2.Add("Electronics");
Console.WriteLine("StringCollection2 요소...");
foreach (string res in strCol2) {
Console.WriteLine(res);
}
Console.WriteLine("두 StringCollection이 같은가? = " + strCol1.Equals(strCol2));
// strCol2의 참조를 strCol3에 할당
StringCollection strCol3 = new StringCollection();
strCol3 = strCol2;
Console.WriteLine("StringCollection3은 StringCollection2와 같은가? = " + strCol3.Equals(strCol2));
}
}실행 결과
StringCollection1 요소... Accessories Books Electronics StringCollection2 요소... Accessories Books Electronics 두 StringCollection이 같은가? = False StringCollection3은 StringCollection2와 같은가? = True
핵심 정리
strCol3 = strCol2;는 새 개체를 만드는 문장이 아니라 strCol2와 동일한 개체를 참조하도록 하는 대입문입니다. 따라서Equals()비교 결과가 True가 됩니다.- StringCollection의
Equals()는 Object 클래스의 기본 구현을 그대로 사용하며 참조 동일성만 검사합니다. - 요소 내용까지 비교하고 싶다면 LINQ의
SequenceEqual()메서드 등을 사용해 두 컬렉션의 요소를 직접 비교해야 합니다.