개발팁2016. 8. 26. 10:46

 

MS-SQL 에 보면, COALESCE 라는 함수가 있다.

(근데, 이거 어떻게 발음하는건가요? 단어가 굉장히 어려워 보이는데..;;)

 

SELECT COALESCE(@a, @b, @c, 'else');

 

앞에서 순서대로 null 이 아닌 값을 찾아오는 함수다.

 

C# 에서도 비슷한 기능을 하는 연산자가 있다.

 

? 라는 연산자는 3항 연산자로 쓰이는데,

 

a == b ? 'same' : 'not same';

 

물음표를 2개 써서,   value1 ?? value2

 

앞에서 순서대로 null 이 아닌 값을 찾는다.

 

물론, 2개 이상의 값에서 찾는다면 , 순서대로 뒤에 ?? 를 나열하면 된다.

 

int? a = null;
int? b = null;
int? c = 100;

int? k = a ?? b ?? c;

int? 는 int 가 primitive type 이기 때문에 null 값이 들어갈 수 없다. int? 는 null 값을 허용한다는 뜻이다.

 

a, b, c 중에 앞에서 순서대로 null 이 아닌 값이 k 에 할당된다.

 

 

if(strV1 != null)

{

    System.out.println("the value is " + strV1);

}

else if(strV2 != null)

{

    System.out.println("the value is " + strV2);

}

else

{

    System.out.println("the value is else");

}

 

if / else 로 구성된 문장은 3항 연산자로 아래와 같이 쓸 수 있다.

 

System.out.println("the value is " + ( strV1 != null ? strV1 : strV2 != null ? strV2 : 'else' ) );

 

이는 다시 ?? 연산자로 아래와 같이 사용이 가능하다.

 

System.out.println("the value is " + ( strV1 ?? strV2 ?? 'else' ) );

 

 

Posted by 헝개