Equailty Operator : 같음 연산자 : ==
같음 연산자 ==는 피연산자가 같으면 ture를 반환하고, 그렇지 않으면 false를 반환합니다.
int a = 1 + 2 + 3;
int b = 6;
Console.WriteLine(a == b); // output: True
char c1 = 'a';
char c2 = 'A';
Console.WriteLine(c1 == c2); // output: False
Console.WriteLine(c1 == char.ToLower(c2)); // output: True
Reference Type Equality : 참조 형식 같음
기본적으로 두 개의 레코드가 아닌 참조 형식 피연산자는 동일한 개체를 참조하는 경우 같습니다.
public class ReferenceTypesEquality
{
public class MyClass
{
private int id;
public MyClass(int id) => this.id = id;
}
public static void Main()
{
var a = new MyClass(1);
var b = new MyClass(1);
var c = a;
Console.WriteLine(a == b); // output: False
Console.WriteLine(a == c); // output: True
}
}
Record Type Equality : 레코드 형식 같음
C# 9.0 이상에서 사용할 수 있는 레코드 형식은 기본적으로 값 같음을 의미 체계를 제공하는 == 및 != 연산자를 지원합니다.
즉 두 개의 레코드 피연산자는 둘 다 null 이거나 모든 필드와 자동 구현 속성의 해당 값이 같은 경우에 같습니다.
public class RecordTypesEquality
{
public record Point(int X, int Y, string Name);
public record TaggedNumber(int Number, List<string> Tags);
public static void Main()
{
var p1 = new Point(2, 3, "A");
var p2 = new Point(1, 3, "B");
var p3 = new Point(2, 3, "A");
Console.WriteLine(p1 == p2); // output: False
Console.WriteLine(p1 == p3); // output: True
var n1 = new TaggedNumber(2, new List<string>() { "A" });
var n2 = new TaggedNumber(2, new List<string>() { "A" });
Console.WriteLine(n1 == n2); // output: False
}
}
앞의 예제에서 알 수 있듯이 레코드가 아닌 참조 형식 멤버의 경우 참조된 인스턴스가 아니라 참조 값이 비교됩니다.
String Equality : 문자열 같음
두 개의 문자열 피연산자가 모두 null 이거나 두 문자열 인스턴스가 같은 길이고 각 문자위치에 동일한 문자가 있을 때 동일합니다.
string s1 = "hello!";
string s2 = "HeLLo!";
Console.WriteLine(s1 == s2.ToLower()); // output: True
string s3 = "Hello!";
Console.WriteLine(s1 == s3); // output: False
Delegate Equality : 대리자 같음
동일한 런타임 형식의 두 delegate 피연산자가 둘 다 null 이거나 해당 호출 목록의 길이가 같고 각 위치에 동일한 항목이 있는 경우 두 피연산자는 같습니다.
Action a = () => Console.WriteLine("a");
Action b = a + a;
Action c = a + a;
Console.WriteLine(object.ReferenceEquals(b, c)); // output: False
Console.WriteLine(b == c); // output: True
의미상 동일한 람다 식의 평가에서 생성된 대리자는 같지 않습니다.
Action a = () => Console.WriteLine("a");
Action b = () => Console.WriteLine("a");
Console.WriteLine(a == b); // output: False
Console.WriteLine(a + b == a + b); // output: True
Console.WriteLine(b + a == a + b); // output: False
Equailty Operator : 같지 않음 연산자 : !=
같지 않음 연산자 != 는 피연산자가 같지 않으면 false를 반환하고 그렇지 않으면 true를 반환합니다.
기본 제공 형식의 피연산자의 경우 식 x != y는 식 !(x==y) 와 동일한 결과를 생성합니다.
int a = 1 + 1 + 2 + 3;
int b = 6;
Console.WriteLine(a != b); // output: True
string s1 = "Hello";
string s2 = "Hello";
Console.WriteLine(s1 != s2); // output: False
object o1 = 1;
object o2 = 1;
Console.WriteLine(o1 != o2); // output: True
'C#' 카테고리의 다른 글
if문 - switch문 (0) | 2023.01.09 |
---|---|
C# Operator_4 : 비교 연산자 (0) | 2023.01.09 |
C# Operator_2 : 부울 논리 연산자 (0) | 2023.01.05 |
C# Operator_1 : 산술 연산자 (0) | 2023.01.04 |
C# Variable : 변수 (0) | 2023.01.03 |