Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1099. C# 10 - (4) 상수 문자열에 포맷 식 사용 가능 [링크 복사], [링크+제목 복사]
조회: 3353
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 15개 있습니다.)

C# 10 - (4) 상수 문자열에 포맷 식 사용 가능

C# 6.0부터 문자열 내에 식을 포함하도록 지원했지만,

string text = $"PI = {Math.PI}";

상수로 선언되는 경우에는 식을 사용하는 표현이 허용되지 않았습니다.

const string PI = "3.141592";

// C# 9 이하에서는 컴파일 오류 - error CS0133: The expression being assigned to 'text' must be constant
const string text = $"PI == {PI}";

// C# 9 이하에서는 컴파일 오류 - error CS0133: The expression being assigned to 'space' must be constant
const string space = $"{ " " }";

하지만, C# 10부터는 위의 표현에서 컴파일 오류가 발생하지 않고 최종 문자열을 계산해 "const string"으로 처리합니다. 또한 포맷식이 허용되므로 상수 문자열을 반환하는 nameof도 사용할 수 있습니다.

using System;
const string systemNamespace = $"{nameof(System)}"; // C# 9 이전에는 CS0133 컴파일 오류

// C# 9.0 이하 - [DebuggerDisplay("class " + nameof(C1))]
[DebuggerDisplay($"class {nameof(C1)}")]
public class C1
{
    // C# 9.0 이하 - [Obsolete("field " + nameof(S1) + " is depreacted")]
    [Obsolete($"field {nameof(S1)} is depreacted")]
    const string S1 = "Hello world";
    const string S2 = "Hello" + " " + "World";
    const string S3 = S1 + " Kevin, welcome to the team!";
}

반면, 박싱/언박싱 및 암시적 참조 변환이 이뤄지는 경우에는 여전히 사용할 수가 없습니다. 즉, 다음과 같은 코드는 유효하지 않습니다.

const float fPI = 3.141592F;
const string text = $"PI == {fPI}"; // 컴파일 오류 error CS0133: The expression being assigned to 'text' must be constant

왜냐하면, 위의 식은 사실 다음과 같이 번역되어야 하므로,

"PI == " + fPI.ToString();

상수식으로 평가할 수 없기 때문입니다. 즉, 간단하게 정리하면 문자열 상수와 문자열 리터럴의 조합에 한해 컴파일 시점에 문자열 식에서 최종 문자열을 상수로써 계산/처리할 수 있게 된 것입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




C# 10 - (1) 구조체를 생성하는 record struct (공식 문서, Static Abstract Members In Interfaces C# 10 Preview)
; https://www.sysnet.pe.kr/2/0/12790

C# 10 - (2) 전역 네임스페이스 선언 (공식 문서, Global Using Directive)
; https://www.sysnet.pe.kr/2/0/12792

C# 10 - (3) 개선된 변수 초기화 판정 (공식 문서, Improved Definite Assignment)
; https://www.sysnet.pe.kr/2/0/12793

C# 10 - (4) 상수 문자열에 포맷 식 사용 가능 (공식 문서, Constant Interpolated Strings)
; https://www.sysnet.pe.kr/2/0/12796

C# 10 - (5) 속성 패턴의 개선 (공식 문서, Extended property patterns)
; https://www.sysnet.pe.kr/2/0/12799

C# 10 - (6) record class 타입의 ToString 메서드를 sealed 처리 허용 (공식 문서, Sealed record ToString)
; https://www.sysnet.pe.kr/2/0/12801

C# 10 - (7) Source Generator V2 APIs (Source Generator V2 APIs)
; https://www.sysnet.pe.kr/2/0/12804

C# 10 - (8) 분해 구문에서 기존 변수의 재사용 가능 (공식 문서, Mix declarations and variables in deconstruction)
; https://www.sysnet.pe.kr/2/0/12805

C# 10 - (9) 비동기 메서드가 사용할 AsyncMethodBuilder 선택 가능 (공식 문서, Async method builder override); 
; https://www.sysnet.pe.kr/2/0/12807

C# 10 - (10) 개선된 #line 지시자 (공식 문서, Enhanced #line directive)
; https://www.sysnet.pe.kr/2/0/12812

C# 10 - (11) Lambda 개선 (공식 문서 1, 공식 문서 2, Lambda improvements) 
; https://www.sysnet.pe.kr/2/0/12813

C# 10 - (12) 문자열 보간 성능 개선 (공식 문서, Interpolated string improvements)
; https://www.sysnet.pe.kr/2/0/12826

C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언 (공식 문서, File-scoped namespace)
; https://www.sysnet.pe.kr/2/0/12828

C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능 (공식 문서, Parameterless struct constructors)
; https://www.sysnet.pe.kr/2/0/12829

C# 10 - (15) CallerArgumentExpression 특성 추가 (공식 문서, Caller expression attribute)
; https://www.sysnet.pe.kr/2/0/12835

Language Feature Status
; https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/14/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13297정성태3/26/202378Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/202396Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지파일 다운로드1
13295정성태3/24/2023107Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/2023120.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/2023105오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/2023108Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/2023125.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/2023175.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/202382Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/202390Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/202390Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/2023695Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/2023129Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/2023137Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/202391오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/2023113Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/2023156Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/2023162개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/2023100오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/2023133개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원
13277정성태3/6/2023153개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/2023224.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/2023216.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/2023223.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/2023258.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...