Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# 7.0에서도 부분적으로 가능해진 "타입 추론을 통한 튜플의 변수명 자동 지정"

C# 7.1 컴파일러부터 "타입 추론을 통한 튜플의 변수명 자동 지정"이 추가되었습니다.

Infer tuple names (aka. tuple projection initializers)
; https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.1/infer-tuple-names.md

제 책에서는 "13.3" 절에 그 내용을 설명하고 있는데요. 관련해서 책에 포함된 예제가 다음의 코드입니다.

int age = 20;
string name = "Kevin Arnold";

var person = (age, name);

Console.WriteLine($"{person.age}, {person.name}");

위의 코드를 C# 7.0 컴파일러에 맞춰놓고 빌드하면 다음과 같은 CS8306 컴파일 오류가 발생합니다.

1>------ Build started: Project: ConsoleApp2, Configuration: Debug Any CPU ------
1>D:\temp\ConsoleApp2\ConsoleApp2\Program.cs(18,41,18,44): error CS8306: Tuple element name 'age' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
1>D:\temp\ConsoleApp2\ConsoleApp2\Program.cs(18,55,18,59): error CS8306: Tuple element name 'name' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

오류 메시지에 보이듯이, 당연히 C# 7.1로 설정하고 빌드하면 정상적으로 컴파일이 됩니다.




그런데 우연히 보게 된 글에서,

Something Wrong In Csharp Tuple
C#의 튜플은 어디서부턴가 잘못되었다
; https://phillyai.github.io/2017-08-22-Something-Wrong-In-Csharp-Tuple/

재미있는 예제를 접했습니다.

using System;
using System.Linq;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] list = { 3, 1, 4, 1, 5, 9, 2 };
            foreach (var (v, i) in list.Select((val, index) => (val, index)))
            {
                Console.WriteLine($"{i}: {v}");
            }
        }
    }
}

위의 예제 코드를 최근의 Visual Studio에서 C# 7.0을 대상으로 빌드하면 정상적으로 빌드가 됩니다. 그런데, 좀 오래된 Visual Studio, 확실하게 15.3.1 버전의 경우에는 C# 7.0을 대상으로 하면 다음과 같은 CS8306 컴파일 오류가 발생합니다.

1>------ Rebuild All started: Project: ConsoleApp2, Configuration: Debug Any CPU ------
1>D:\temp\ConsoleApp2\ConsoleApp2\Program.cs(14,13,17,14): error CS8306: Tuple element name 'val' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
1>D:\temp\ConsoleApp2\ConsoleApp2\Program.cs(14,13,17,14): error CS8306: Tuple element name 'index' is inferred. Please use language version 7.1 or greater to access an element by its inferred name.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

동일하게 "CS8306: Tuple element name '...' is inferred" 컴파일 오류인데, 최근의 C# 컴파일러에서는 7.0으로 맞춰놓고 해도 정상적으로 빌드가 되는 것입니다. 제 예상으로는, roslyn 컴파일러의 소스 코드를 7.1 이후에 수정을 하다가 C# 7.0 모드에서도 튜플에 대한 변수명이 추론이 되도록 하는 (좋은) 부작용이 발생한 것으로 보입니다.




일반적인 상황에서는 전혀 중요하지 않은 이야기인데... 혹시나 관련 소스 코드를 빌드하면서 C# 7.0에도 튜플 추론이 잘 된다고 메일을 보내실 독자분을 위해 미리 쉴드성 글을 남깁니다. ^^




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







[최초 등록일: ]
[최종 수정일: 5/11/2018]

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

비밀번호

댓글 작성자
 




... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12477정성태1/5/202113627기타: 79. github 코드 검색 방법 [1]
12476정성태1/5/202110294.NET Framework: 996. C# - 닷넷 코어에서 다른 스레드의 callstack을 구하는 방법파일 다운로드1
12475정성태1/5/202112875.NET Framework: 995. C# - Span<T>와 Memory<T> [1]파일 다운로드1
12474정성태1/4/202110406.NET Framework: 994. C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 [1]파일 다운로드1
12473정성태1/4/20219213.NET Framework: 993. .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무 [1]파일 다운로드1
12472정성태1/3/20219497디버깅 기술: 178. windbg - 디버그 시작 시 스크립트 실행
12471정성태1/1/20219986.NET Framework: 992. C# - .NET Core 3.0 이상부터 제공하는 runtimeOptions의 rollForward 옵션 [1]
12470정성태12/30/202010152.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [1]파일 다운로드1
12469정성태12/30/202013737.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스 [1]파일 다운로드1
12468정성태12/30/202010353Windows: 186. CMD Shell의 "Defaults"와 "Properties"에서 폰트 정보가 다른 문제 [1]
12467정성태12/29/202010258.NET Framework: 989. HttpContextAccessor를 통해 이해하는 AsyncLocal<T> [1]파일 다운로드1
12466정성태12/29/20208250.NET Framework: 988. C# - 지연 실행이 꼭 필요한 상황이 아니라면 singleton 패턴에서 DCLP보다는 static 초기화를 권장파일 다운로드1
12465정성태12/29/202011382.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
12464정성태12/29/202010229.NET Framework: 986. pptfont.exe - PPT 파일에 숨겨진 폰트 설정을 일괄 삭제
12463정성태12/29/20209275개발 환경 구성: 520. RDP(mstsc.exe)의 다중 모니터 옵션 /multimon, /span
12462정성태12/27/202010906디버깅 기술: 177. windbg - (ASP.NET 환경에서 유용한) netext 확장
12461정성태12/21/202011733.NET Framework: 985. .NET 코드 리뷰 팁 [3]
12460정성태12/18/20209424기타: 78. 도서 소개 - C#으로 배우는 암호학
12459정성태12/16/20209829Linux: 35. C# - 리눅스 환경에서 클라이언트 소켓의 ephemeral port 재사용파일 다운로드1
12458정성태12/16/20209329오류 유형: 694. C# - Task.Start 메서드 호출 시 "System.InvalidOperationException: 'Start may not be called on a task that has completed.'" 예외 발생 [1]
12457정성태12/15/20208874Windows: 185. C# - Windows 10/2019부터 추가된 SIO_TCP_INFO파일 다운로드1
12456정성태12/15/20209157VS.NET IDE: 156. Visual Studio - "Migrate packages.config to PackageReference"
12455정성태12/15/20208681오류 유형: 693. DLL 로딩 시 0x800704ec - This Program is Blocked by Group Policy
12454정성태12/15/20209247Windows: 184. Windows - AppLocker의 "DLL Rules"를 이용해 임의 경로에 설치한 DLL의 로딩을 막는 방법 [1]
12453정성태12/14/202010228.NET Framework: 984. C# - bool / BOOL / VARIANT_BOOL에 대한 Interop [1]파일 다운로드1
12452정성태12/14/202010426Windows: 183. 설정은 가능하지만 구할 수는 없는 TcpTimedWaitDelay 값
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...