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

(시리즈 글이 12개 있습니다.)
닷넷: 2342. C# 14 - (취소된 글)
; https://www.sysnet.pe.kr/2/0/13970

닷넷: 2343. C# 14 - (1) 속성 구문에서 문맥 키워드로 추가되는 field 예약어
; https://www.sysnet.pe.kr/2/0/13971

닷넷: 2346. C# 14 - (2) Span 타입과 배열 간의 암시적 형변환
; https://www.sysnet.pe.kr/2/0/13974

닷넷: 2347. C# 14 - (3) 형식 인자가 없는 제네릭 타입의 nameof 지원
; https://www.sysnet.pe.kr/2/0/13975

닷넷: 2349. C# 14 - (4) 문자열 리터럴을 utf-8 인코딩으로 저장
; https://www.sysnet.pe.kr/2/0/13977

닷넷: 2350. C# 14 - (5) 람다 매개 변수에 접근자가 있는 경우에도 타입 생략 가능
; https://www.sysnet.pe.kr/2/0/13986

닷넷: 2351. C# 14 - (6) event와 생성자에도 partial 메서드 적용
; https://www.sysnet.pe.kr/2/0/13987

닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가
; https://www.sysnet.pe.kr/2/0/13998

닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능
; https://www.sysnet.pe.kr/2/0/13999

닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
; https://www.sysnet.pe.kr/2/0/14003

닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원
; https://www.sysnet.pe.kr/2/0/14008

닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용
; https://www.sysnet.pe.kr/2/0/14009




C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용

드디어 C# 14의 마지막 기능입니다. ^^

[Proposal]: Support optional and named arguments in Expression trees
; https://github.com/dotnet/csharplang/issues/9246

Support optional and named arguments in Expression trees
; https://github.com/dotnet/csharplang/blob/main/proposals/csharp-14.0/optional-and-named-parameters-in-expression-trees.md

이번 글의 내용도 실습을 하려면 현재(2025-08-28) Visual Studio 2022 Preview 버전을 필요로 합니다.




스펙 문서에 실린 예제 코드만 봐도 이에 대해 금방 이해할 수 있는데요,

using System.Linq.Expressions;

internal class Program
{
    static void Main(string[] args)
    {
        Expression<Func<int?[], int, bool>> e;

        // Expression Tree용의 람다 식에서는 선택적 인수 (X)
        e = (a, i) => a.Contains(i); // error CS0854: expression tree may not contain a call that uses optional arguments

        // Expression Tree용의 람다 식에서는 명명된 인수 (X)
        e = (a, i) => a.Contains(i, comparer: null); // error CS0853: expression tree may not contain a named argument specification
    }
}

public static class MemoryExtensions
{
    // 3번째 인자가 기본 값을 담고 있어 생략 가능한 유형의 메서드
    public static bool Contains<T>(this ReadOnlySpan<T> span, T value, IEqualityComparer<T>? comparer = null)
    {
        if (comparer == null)
        {
            comparer = EqualityComparer<T>.Default;
        }

        foreach (var item in span)
        {
            if (comparer.Equals(item, value))
            {
                return true;
            }
        }

        return false;
    }
}

바로 저 소스 코드가 C# 14부터는 정상적으로 컴파일이 됩니다. 참고로, 해당 표현식을 Expression Tree가 아닌 Delegate로 바꾸면 C# 13 이전 버전에서도 문제가 없습니다.

public delegate bool FuncDelegate<T>(ReadOnlySpan<T> span, T value);

// 동일한 람다 식을 Expression Tree가 아닌 Delegate로 처리하는 것은,

FuncDelegate<int> e1 = (a, i) => a.Contains(i); // C# 13 이전에도 OK
FuncDelegate<int> e2 = (a, i) => a.Contains(i, comparer: null); // C# 13 이전에도 OK

Console.WriteLine(e1(new int[] { 1, 2, 3 }, 2)); // True
Console.WriteLine(e2(new int[] { 1, 2, 3 }, 4)); // False




사실 이번 기능도 이전에 실습하지 않았다면 그냥 자연스럽게 모르고 지나갈 수 있었던 규칙입니다. 마이크로소프트조차도 이에 대해 다음과 같은 글을 남겼는데요,

It's unclear why the restrictions were added originally. An initial investigation hasn't revealed an issue supporting these cases.


그러니까, 원래라면 당연히 허용되었을 기능이었던 것입니다. 게다가 또 하나 재미있는 것은, 문서의 예제에서는 2개 모두 컴파일 오류가 발생한다고 하지만,

// Visual Studio 2022 + C# 13 이전으로 빌드 시,

e = (a, i) => a.Contains(i); // 빌드 OK
e = (a, i) => a.Contains(i, comparer: null); // error CS0853: expression tree may not contain a named argument specification

실제로는 저렇게 선택적 인수를 사용한 코드는 빌드에 문제가 없었습니다. 오히려 저 코드가 오류로 빌드되는 것은 Visual Studio 2022 + C# 14 preview 환경에서만 발생하는 문제입니다. 아마도 C# 14의 기능을 개선하면서 선택적 인수의 빌드에 preview 버전부터 발생하던 것을 오해하는 바람에 그대로 문서에 실은 것이 아닌가 싶습니다.

즉, 아래와 같은 코드가 C# 13 이전에는 정상적으로 빌드가 됩니다.

using System.Linq.Expressions;

internal class Program
{
    static void Main(string[] args)
    {
        Expression<Func<int?[], int, bool>> e;

        // Visual Studio 2022 + C# 13 이전 환경에서도,
        e = (a, i) => a.Contains(i); // 빌드 OK
        var func = e.Compile();

        Console.WriteLine(func(new int?[] { 1, 2, 3 }, 2)); // True
        Console.WriteLine(func(new int?[] { 1, 2, 3 }, 4)); // False
    }
}

그런 의미에서, 어쩌면 원래 이 글의 제목은 "Support optional and named arguments in Expression trees"라고 하는 것이 맞을 듯합니다.




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







[최초 등록일: ]
[최종 수정일: 8/28/2025]

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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  [112]  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11212정성태5/26/201725924오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201724349오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201724662기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201773477Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201730602오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201732381Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201725438오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201724826.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201734405개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201721227오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201722662오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201726841오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201723522오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201723828.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
11198정성태5/10/201726827.NET Framework: 656. Windows Forms의 오류(Exception) 처리 방법에 대한 차이점 설명
11197정성태5/8/201722009개발 환경 구성: 315. VHD 파일의 최소 크기파일 다운로드1
11196정성태5/4/201723761오류 유형: 384. Msvm_ImageManagementService WMI 객체를 사용할 때 오류 상황 정리 [1]
11195정성태5/3/201725026.NET Framework: 655. .NET Framework 4.7 릴리스
11194정성태5/3/201725890오류 유형: 383. net use 명령어로 네트워크 드라이브 연결 시 "System error 67 has occurred." 오류 발생
11193정성태5/3/201723507Windows: 141. 설치된 Windows로부터 설치 이미지를 만드는 방법
11192정성태5/2/201725809Windows: 140. unattended.xml/autounattend.xml 파일을 마련하는 방법
11191정성태5/2/201726738Windows: 139. Dell Venue 8 Pro 태블릿에 USB를 이용한 윈도우 운영체제 설치 방법
11190정성태5/2/201732205Windows: 138. Windows 운영체제의 ISO 설치 파일에 미리 Device driver를 준비하는 방법
11189정성태5/2/201722933Windows: 137. Windows 7 USB/DVD DOWNLOAD TOOL로 98%에서 실패하는 경우
11188정성태4/27/201726075VC++: 118. Win32 HANDLE 자료형의 이모저모 [2]
11187정성태4/26/201727250개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [1]파일 다운로드1
... 106  107  108  109  110  111  [112]  113  114  115  116  117  118  119  120  ...