[ ?. 연산자 ]
[ 의미 ]
?. 연산자는 Null 이 아니라면 참조하고 , Null 이라면 Null 로 처리한다 .
[ 예시 ]
class Student
{
public string MyName;
};
static void Main( string[] args )
{
Student Yeo = new Student();
Console.WriteLine( Yeo?.MyName );
// null이 아니라 MyName을 참조한다 .
Student Kim = null;
Console.WriteLine( Kim?.MyName );
// 아무것도(null) 출력되지 않음.
}
[ ??연산자 ]
[ 의미 ]
?? 연산자는 Null 오른쪽 값으로 처리한다 .
[ 예시 ]
string YeoName = "Yeo"
string name1 = YeoName ?? "NoName";
Console.WriteLine( name1 );
// "Yeo"출력
string Kim = null
string name2 = Kim ?? "NoName";
Console.WriteLine( name2 );
// "NoName"출력
[ ??연산자 와 ?. 연산자]
[ 의미 ]
?? 연산자와 ?. 연산자는 함께 할때 null 구문을 줄일 수 있어 유용하다 .
[ 예시 ]
static int GetStudentCount<T>( List<T> _students )
{
return _students?.Count ?? 0;
}
static void Main( string[] args )
{
List<string> students1 = new List<string>();
a.Add( "Kim" );
a.Add( "Yeo" );
a.Add( "Lee" );
Console.WriteLine( GetStudentCount( students1 ) );
// 3 출력됨
List<string> students2 = null;
Console.WriteLine( GetStudentCount( b ) );
// 0 출력됨
}
'C#' 카테고리의 다른 글
[ C# ]Conditional Attribute (0) | 2023.06.26 |
---|---|
[ C# ] foreach 문을 돌리며 리스트 안에 객체를 삭제시 주의점 (0) | 2023.04.05 |
[c#] 배열을 딕셔너리로 만들고 인덱스에 따라 정렬하여 사용하기 (0) | 2023.04.04 |
[C#]sealed 한정자 (0) | 2023.03.02 |
[ C# ] Enum 결합하여 사용하기 (0) | 2023.02.22 |