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

비밀번호

댓글 작성자
 




... 166  167  168  169  170  171  172  173  174  [175]  176  177  178  179  180  ...
NoWriterDateCnt.TitleFile(s)
720정성태5/13/200927792오류 유형: 80. SQL Server 2008 - Package 실행 오류의 구체적인 원인 확인
719정성태5/12/200929184.NET Framework: 134. WPF - XBAP을 호스팅하고 있는 인터넷 익스플로러 인터페이스 구하기파일 다운로드1
717정성태5/11/200929403개발 환경 구성: 44. VHD 파일 크기 확장하는 방법 - 두 번째 이야기
714정성태5/7/200927897Windows: 45. Windows 7 RC와 함께 공개된 Windows Virtual PC 베타
713정성태4/30/200959543오류 유형: 79. DLL 'xxxxx.dll'을(를) 로드할 수 없습니다. [1]
712정성태4/28/200932325오류 유형: 78. Windows Vista/2008에서의 MSXML4.cab 파일 배포 문제
711정성태4/27/200932160개발 환경 구성: 43. Hyper-V VHD 파일 크기 확장하는 방법
710정성태4/26/200932871.NET Framework: 133. CallbackOnCollectedDelegate was detected [4]파일 다운로드1
709정성태4/24/200928831개발 환경 구성: 42. Windows Vista SP1에서 사용 가능한 Hyper-V 관리 도구
708정성태4/23/200933572.NET Framework: 132. ClickOnce 배포를 명령행 수작업 구성파일 다운로드1
707정성태4/22/200933028개발 환경 구성: 41. Hyper-V에 Linux 설치 - SUSE Linux Enterprise Server 11
706정성태4/21/200928860.NET Framework: 131. ClickOnce - 그룹화시켜 다운로드파일 다운로드1
705정성태4/20/200924562개발 환경 구성: 40. TFS2008 SP1의 DBTier에 SQL Server 2008 SP1 설치 [1]
704정성태4/19/200924426개발 환경 구성: 39. Together 2007 SP1 설치
702정성태4/18/200936071.NET Framework: 130. Infragistics - Tabbed MDI WPF 응용 프로그램파일 다운로드1
701정성태4/17/200930855Windows: 44. bootsect 오류 - Access is denied.
700정성태4/17/200933982.NET Framework: 129. Infragistics WPF 컨트롤 사용 [1]
699정성태4/16/200931811.NET Framework: 128. 이벤트 멤버의 명시적 구현파일 다운로드1
696정성태4/12/200931264오류 유형: 77. RDP 연결이 되지 않는 경우. [1]
693정성태4/9/200925929오류 유형: 76. "Client found response content type of '', but expected 'text/xml'. The request failed with an empty response.No Reports".
692정성태4/8/200938874.NET Framework: 127. ClickOnce로 ActiveX를 같이 배포하는 방법 [2]파일 다운로드1
690정성태4/5/200926692오류 유형: 75. Event Viewer - The data is invalid (13)
688정성태4/5/200932649VS.NET IDE: 60. Output 경로에 매크로 상수 사용하는 방법 [1]
687정성태4/5/200926564.NET Framework: 126. Composite Application Guidance for WPF and Silverlight
689정성태4/5/200926741    답변글 .NET Framework: 126.1. CAG - 빌드 환경 구성파일 다운로드1
691정성태4/6/200926385    답변글 .NET Framework: 126.2. CAG - Shell 띄우기파일 다운로드1
... 166  167  168  169  170  171  172  173  174  [175]  176  177  178  179  180  ...