Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 7개 있습니다.)

C# 7.3에서 개선된 문법 4개(Support == and != for tuples, Ref Reassignment, Constraints, Stackalloc initializers)

C# 7.3 (1) - 개선된 문법 4개(Support == and != for tuples, Ref Reassignment, Constraints, Stackalloc initializers)
; https://www.sysnet.pe.kr/2/0/11552

C# 7.3 (2) - 개선된 메서드 선택 규칙 3가지(Improved overload candidates)
; https://www.sysnet.pe.kr/2/0/11553

C# 7.3 (3) - 자동 구현 속성에 특성 적용 가능(Attribute on backing field)
; https://www.sysnet.pe.kr/2/0/11554

C# 7.3 (4) - 사용자 정의 타입에 fixed 적용 가능(Custom fixed)
; https://www.sysnet.pe.kr/2/0/11555

C# 7.3 (5) - 구조체의 고정 크기를 갖는 fixed 배열 필드에 대한 직접 접근 가능(Indexing movable fixed buffers)
; https://www.sysnet.pe.kr/2/0/11556

C# 7.3 (6) - blittable 제네릭 제약(blittable)
; https://www.sysnet.pe.kr/2/0/11558

C# 7.3 (7) - 초기화 식에서 변수 사용 가능(expression variables in initializers)
; https://www.sysnet.pe.kr/2/0/11560




지난 5월 8일에 있었던 Visual Studio 15.7 업데이트부터 C# 7.3이 지원되기 시작했습니다. (적용 방법은 이렇게!) 이전의 C# 7.2가 struct를 위주로 한 주요 업데이트가 있었다는 특징을 지녔던 반면, C# 7.3의 경우 특정 목적을 두지는 않고 편의성을 높인 업데이트가 주류를 이루고 있습니다. 아래의 문서에 보면,

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

C# 7.3으로 총 11개의 특징이 있는데 그중에서 아래의 글에서도 미리 소개한,

Microsoft Build 2018 - The future of C# 동영상 내용 정리
; https://www.sysnet.pe.kr/2/0/11536

4개의 기능을 이 글에서 다시 간략하게 정리해 보겠습니다.

  • Support == and != for tuples
  • Ref Reassignment
  • Constraints
  • Stackalloc initializers





Support == and != for tuples

우선, tuple 타입에 대해 ==, != 비교 연산자에 대한 지원이 추가되었습니다. 따라서, C# 7.2 이전에는 다음의 코드를 컴파일할 수 없지만,

using System;

class Program
{
    static void Main(string[] args)
    {
        var tuple = (13, "Kevin");

        // C# 7.2까지 컴파일 오류 - Error CS0019 Operator '==' cannot be applied to operands of type '(int, string)' and '(int, string)'
        bool result1 = tuple == (13, "Winnie");

        // C# 7.2까지 컴파일 오류 - Error CS0019 Operator '!=' cannot be applied to operands of type '(int, string)' and '(int, string)'
        bool result2 = tuple != (13, "Winnie");
    }
}

C# 7.3부터는 정상적으로 컴파일할 수 있습니다. 비법은 간단합니다. C# 7.3 컴파일러는 위의 비교 코드를 개별 필드에 대한 비교 코드로 확장해서 처리합니다.

bool result1 = (tuple.Item1 == 13) && (tuple.Item2 == "Winnie");

bool result2 = (tuple.Item1 != 13) || (tuple.Item2 != "Winnie");





Ref Reassignment

C# 7.0부터 추가된 ref 로컬 변수가 C# 7.2까지는 재할당을 허용하지 않았습니다.

static void Main(string[] args)
{
    int a = 5;
    ref int b = ref a; // ref 로컬 변수 b

    int c = 6;

    // C# 7.2까지 컴파일 오류 - Error CS1073 Unexpected token 'ref'
    b = ref c; // 새롭게 변수 c에 대한 ref를 할당
}

하지만 C# 7.3 컴파일러부터 이를 허용합니다.





Constraints

제네릭 관련한 where 제약에 Delegate, Enum과 unmanaged가 추가되었습니다. 따라서 다음과 같은 식의 제약을 추가하는 것이 가능합니다.

unsafe void M<D, E, T>(D d, E e, T* pointer) where D : Delegate
                        where E: Enum
                        where T: unmanaged
{
    // ... [생략]...
}

C# 7.2 이하에서는 위의 코드를 컴파일하면 다음과 같은 오류가 발생했습니다.

  • Error CS0702 Constraint cannot be special class 'Delegate'
  • Error CS0702 Constraint cannot be special class 'Enum'
  • Error CS0246 The type or namespace name 'unmanaged' could not be found (are you missing a using directive or an assembly reference?)





Stackalloc initializers

stackalloc은 C# 1.0부터 제공하던 예약어였지만, 배열 초기화 구문은 C# 7.3에 와서야 제공이 됩니다.

{
    Span<int> span1 = stackalloc int[5] { 1, 2, 3, 4, 5 };
    Span<int> span2 = stackalloc int[] { 1, 2, 3, 4, 5 };
}

{
    int *pArray1 = stackalloc int[3] { 1, 2, 3 };
    int *pArray2 = stackalloc int[] { 1, 2, 3 };
}

아마도 C# 7.2의 Span 덕분에 스택 상의 배열에 대한 구문 사용이 늘어날 것을 예상하면서 편의상 추가한 것으로 보입니다.




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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/25/2018]

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)
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241877닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241545닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241678닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241558닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241564닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241644닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241624닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241636닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241546닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241608닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241632오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241646디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241647오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241745닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241748디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242626오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241821닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241621Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241957닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...