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

비밀번호

댓글 작성자
 




... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12854정성태11/13/202118067개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/202116480오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/202118675스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/202120983오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/202120624스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/202118672스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/202120070스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/202121382스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/202118427.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/202117453오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/202117304스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202137055오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/202120139스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/202118579.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/202122653.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/202121871.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/202117609VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/202118031Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/202119899.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/202119896오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/202115735VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/202119952VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/202115036VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/202121389오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202122139.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/202118091.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...