본문 바로가기

C#

[ C# ] ?.. / ?? 연산자

[ ?. 연산자 ]

[ 의미 ]

?. 연산자는 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 출력됨
        }