소소한 개발 공부

[C#] 물음표 ?? / ??= / ?. / ? 본문

프로그래밍/C#

[C#] 물음표 ?? / ??= / ?. / ?

이내내 2023. 2. 2. 22:02

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이라면 오른쪽 값을 왼쪽 변수에 할당해주는 기능을 한다.

 

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

 

?? 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