소소한 개발 공부
[C#] 물음표 ?? / ??= / ?. / ? 본문
C#을 공부하다 보면 ??, ?., ? 을 만나게 되는 경우가 왕왕 있는데, 이에 대해서 알아보도록 하자.
?? : Null 병합 연산자 (null-coalescing operators)
사용 방식은 아래와 같다.
A ?? B;
A가 null이면 B 값을 반환한다.
예시 는 아래와 같다.
string a = null;
Console.WriteLine(a ?? "a is null");
// 출력: a is null
----
static void Main()
{
string a = null;
Console.WriteLine(nullMethod(a));
}
public static string nullMethod(string val)
{
return val ?? "val is null";
}
// 출력: val is null
왼쪽 피연산자가 null이라면 오른쪽 값을 반환하기 때문에 오른쪽 값은 null을 넣을 수 없는 것처럼 생각했지만,
오른쪽 피연산자도 null이 되어도 된다. 그럼 그냥 null을 반환한다.
null 병합 연산자를 중첩해서 사용할 수도 있다.
string a = null;
string b = null;
Console.WriteLine(a ?? b ?? "a, b null");
// 출력: a, b null
a ?? b ?? "a, b null" 은 아래와 같은 관계로 연산한다.
a ?? (b ?? "a, b null") -> a ?? "a, b null" -> "a, b null"
??= : null 병합 할당자
A ??= B 와 같이 사용한다.
이 코드는 원래는 다음과 같다.
if (A == null)
{
A = B;
}
위처럼 왼쪽 값이 null이라면 오른쪽 값을 왼쪽 변수에 할당해주는 기능을 한다.
?? and ??= operators - null-coalescing operators
The `??` and `??=` operators are the C# null-coalescing operators. They return the value of the left-hand operand if it isn't null. Otherwise, they return the value of the right-hand operand
learn.microsoft.com
?. , ?[]: Null 조건 연산자 (Null-conditional operators)
a?.b 로 사용한다.
a가 null이 아니라면 a의 멤버인 b를 사용한다는 의미이다.
반대로 a가 null이라면 null을 반환한다.
string a = null;
Console.WriteLine(a?.Length);
// 출력:
a 는 null이므로 a?.Length도 null이라 null을 출력한다.
a?[index] 로 사용한다.
a라는 배열의 index 위치가 null이라면 a?[index]는 null이다.
string a = null;
Console.WriteLine(a?[0]);
// 출력:
a는 null이므로 a?[0]도 null이라 null을 출력한다.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators
Member access operators and expressions
C# operators that you use to access type members. These operators include the dot operator - `.`, indexers - `[`, `]`, `^` and `..`, and invocation - `(`, `)`.
learn.microsoft.com
? : 3차 조건부 연산자 (ternary conditional operator)
위의 null 관련 연산자들과는 다른 3항 연산자이다.
a ? b : c; 로 사용한다.
a 가 true라면 b를, false라면 c를 반환한다.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
?: operator - the ternary conditional operator
Learn about the C# ternary conditional operator, (`?:`), that returns the result of one of the two expressions based on a Boolean expression's result.
learn.microsoft.com
'프로그래밍 > C#' 카테고리의 다른 글
[프로그래머스 | C#] 명예의 전당 (1) List.Sort, heap 삽입-제거 구현 (0) | 2023.02.04 |
---|---|
[C#] 문자열 처리 [자리표시자, 문자열 보간] (0) | 2023.02.02 |
[프로그래머스 | C#] 과일 장수 Sort (2) | 2023.02.01 |
[프로그래머스 | C#] 가장 가까운 같은 글자 LastIndexOf (0) | 2023.01.30 |
[프로그래머스 | C#] 크기가 작은 부분 문자열 TryParse (0) | 2023.01.29 |