== 연산자(C# 참조)

업데이트: 2007년 11월

미리 정의된 값 형식의 경우 같음 연산자(==)는 피연산자의 값이 같으면 true를 반환하고 그렇지 않으면 false를 반환합니다. string 형식을 제외한 참조 형식의 경우 == 연산자는 두 피연산자가 동일한 개체를 참조하면 true를 반환합니다. string 형식의 경우 == 연산자는 문자열 값을 비교합니다.

설명

사용자 정의 값 형식으로 == 연산자를 오버로드할 수 있습니다(operator 참조). 사용자 정의 참조 형식으로도 오버로드할 수 있지만, 기본적으로 == 연산자는 미리 정의된 형식과 사용자 정의 참조 형식 모두에 대해 위에서 설명한 것처럼 동작합니다. == 연산자를 오버로드할 경우에는 != 연산자도 오버로드해야 합니다. 정수 계열 형식에 대한 연산은 일반적으로 열거형에서 허용됩니다.

예제

class Equality
{
    static void Main()
    {
        // Numeric equality: True
        Console.WriteLine((2 + 2) == 4);

        // Reference equality: different objects, 
        // same boxed value: False.
        object s = 1;
        object t = 1;
        Console.WriteLine(s == t);

        // Define some strings:
        string a = "hello";
        string b = String.Copy(a);
        string c = "hello";

        // Compare string values of a constant and an instance: True
        Console.WriteLine(a == b);

        // Compare string references; 
        // a is a constant but b is an instance: False.
        Console.WriteLine((object)a == (object)b);

        // Compare string references, both constants 
        // have the same value, so string interning
        // points to same reference: True.
        Console.WriteLine((object)a == (object)c);
    }
}
/*
Output:
True
False
True
False
True
*/

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 연산자

기타 리소스

C# 참조