It’s me

October 10, 2007

C#의 조건연산자(?:)와 Null-Coalescing 연산자(??)

Filed under: C# — rothmans @ 11:07 am

변수를 할당하는 방법중에 일반적으로 조건연산자를 사용합니다. 하지만 변수가 Null이 아닌경우에만 사용이 가능합니다. 만약 C#에서 Null인 경우에는 다음과 같이 조건연산자를 사용합니다

string strValue = oldValue != null ? oldValue : "변수 값";

oldValue 가 Null 이 아닌 경우에는, strValue 에 oldValue 가 할당되고, 이외에는 strValue에 “변수 값”이 할당됩니다.

이것은 Null-Coalescing 연산자를 사용하여 다음과 같이 구현합니다

string strValue = oldValue ?? "변수 값";

이 로직은 동일합니다. oldValue가 Null 이 아니면, strValue 변수에 oldValue가 할당됩니다.

또한 Null-Coalescing 연산자는 여러가지 Null 유형에 대한 지원이 제공됩니다.

int? count = null;

int strValue = count ?? default (int);

count가 null이면, strValue에는 Integer 유형의 기본값이 할당됩니다(int 기본값인 0으로)

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.