Programming/C# - Window
C#/ Null 연산자
esoog Polaris
2023. 6. 27. 11:27
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Operator | |
{ | |
class MainApp | |
{ | |
static void Main(string[] args) | |
{ | |
string result = (10 % 2) == 0 ? "짝수" : "홀수"; | |
// 조건식 ? a : b; 는 조건식 참일 때 a, 거짓일 때 b 반환. | |
// 조건 연산자. 삼항 연산식 | |
Console.WriteLine(result); | |
ArrayList a = null; | |
a?.Add("야구"); | |
// 객체?.x 에서 .?은 객체의 null 조건부 연산자. | |
// 객체가 null값이면 객체 출력. 값이 있으면 .? 뒤의 x 멤버 접근 | |
// 따라서 위 식에서는 Add()가 호출되지 않는다. | |
a?.Add("축구"); | |
Console.WriteLine($"Count : {a?.Count}"); | |
Console.WriteLine($"{a?[0]}"); | |
Console.WriteLine($"{a?[1]}"); | |
a = new ArrayList(); | |
// 여기서 a는 새로운 객체를 할당 받았다. null과 다르다. | |
a?.Add("야구"); | |
a?.Add("축구"); | |
Console.WriteLine($"Count : {a?.Count}"); | |
Console.WriteLine($"{a?[0]}"); | |
Console.WriteLine($"{a?[1]}"); | |
int? num = null; | |
Console.WriteLine($"{num ?? 0}"); | |
// a ?? b 에서 ?? 은 null 병합 연산자. | |
// a가 null이면 b, 아니면 a 값 반환. | |
// null 값을 대체 시키는 용도로 보면 되겠다. | |
num = 99; | |
Console.WriteLine($"{num ?? 0}"); | |
string str = null; | |
Console.WriteLine($"{str ?? "Default"}"); | |
str = "Specific"; | |
Console.WriteLine($"{str ?? "Default"}"); | |
} | |
} | |
} |
반응형