C# operator 사용시 주의 사항

2011. 5. 3. 08:41C# And Unity

http://stackoverflow.com/questions/1766492/c-overloading-operator-versus-equals

c#은 virtual 이 선언되어 있지 않은 경우에 compile time에 어떤 method가 사용될지 결정됩니다.
operator 는 virtual이 아니기 때문에 아래와 같은 경우 답이 다르게 나오게 됩니다.
이것이 연산자 오버로딩의 장점이자 단점입니다.
readability가 늘어나기 때문에 보기에는 편한데, 의미가 달라질 수 있기 때문에 사용에 주의해야 합니다.
그래서 java에서는 이처럼 편한 연산자 오버로딩을 빼버린 것이죠.

object x = "hello";
object y = 'h' + "ello"; // ensure it's a different reference

if (x == y) { // evaluates to FALSE
string x = "hello";
string y = 'h' + "ello"; // ensure it's a different reference

if (x == y) { // evaluates to TRUE
설명하자면 operator overloading은 virtual method가 아니기 때문에
위의 것은 object.operator==()를 호출하고, 아래의 것은 String.operator==() 를 호출하게 되기 때문이죠.
그래서 값을 비교할 경우에는 Equals를 호출하셔야 합니다.

Java와 비교했을때 다른 점은 java의 == 는 무조건 reference 만을 비교하지만
C#은 어떤 Class의 == operator를 호출하느냐에 따라 결과가 달라지는 것이죠.
그래서 Java와 동일하게 reference equality를 비교하고자 할때는 System.Object.ReferenceEquals() 를 사용하고
값을 비교하고자 할때는 Java와 동일하게 Equals() 함수를 사용하시면 됩니다.

object x = "hello";
object y = 'h' + "ello"; // ensure it's a different reference

if (x.Equals(y)) { // evaluates to TRUE
string x = "hello";
string y = 'h' + "ello"; // ensure it's a different reference

if (x.Equals(y)) { // also evaluates to TRUE