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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12302정성태8/30/202022336.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202020568오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/202022301.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202022411.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
12298정성태8/27/202022476오류 유형: 640. livekd - Could not resolve symbols for ntoskrnl.exe: MmPfnDatabase
12297정성태8/25/202022017개발 환경 구성: 503. SHA256 테스트 인증서 생성 방법
12296정성태8/24/202023364.NET Framework: 933. C# - ETW 관련 Win32 API 사용 예제 코드 (2) NT Kernel Logger파일 다운로드1
12295정성태8/24/202022006오류 유형: 639. Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket ,,,
12293정성태8/24/202022965Windows: 171. "Administered port exclusions" 설명
12292정성태8/20/202026714.NET Framework: 932. C# - ETW 관련 Win32 API 사용 예제 코드 (1)파일 다운로드2
12291정성태8/15/202022367오류 유형: 638. error 1297: Device driver does not install on any devices, use primitive driver if this is intended.
12290정성태8/11/202024200.NET Framework: 931. C# - IP 주소에 따른 국가별 위치 확인 [8]파일 다운로드1
12289정성태8/6/202021136개발 환경 구성: 502. Portainer에 윈도우 컨테이너를 등록하는 방법
12288정성태8/5/202017901오류 유형: 637. WCF - The protocol 'net.tcp' does not have an implementation of HostedTransportConfiguration type registered.
12287정성태8/5/202021388오류 유형: 636. C# - libdl.so를 DllImport로 연결 시 docker container 내에서 System.DllNotFoundException 예외 발생
12286정성태8/5/202023123개발 환경 구성: 501. .NET Core 용 container 이미지 만들 때 unzip이 필요한 경우
12285정성태8/4/202020853오류 유형: 635. 윈도우 10 업데이트 - 0xc1900209 [2]
12284정성태8/4/202020347디버깅 기술: 169. Hyper-V의 VM에 대한 메모리 덤프를 뜨는 방법
12283정성태8/3/202022967디버깅 기술: 168. windbg - 필터 드라이버 확인하는 확장 명령어(!fltkd) [2]
12282정성태8/2/202019313디버깅 기술: 167. windbg 디버깅 사례: AppDomain 간의 static 변수 사용으로 인한 crash (2)
12281정성태8/2/202024022개발 환경 구성: 500. (PDB 연결이 없는) DLL의 소스 코드 디버깅을 dotPeek 도구로 해결하는 방법
12280정성태8/2/202020584오류 유형: 634. 오라클 (평생) 무료 클라우드 VM 생성 후 SSH 접속 시 키 오류 발생 [2]
12279정성태7/29/202024028개발 환경 구성: 499. 닷넷에서 접근해보는 InterSystems의 Cache 데이터베이스파일 다운로드1
12278정성태7/23/202019476VS.NET IDE: 149. ("Binary was not built with debug information" 상태로) 소스 코드 디버깅이 안되는 경우
12277정성태7/23/202022208개발 환경 구성: 498. DEVPATH 환경 변수의 사용 예 - .NET Reflector의 (PDB 연결이 없는) DLL의 소스 코드 디버깅
12276정성태7/23/202022034.NET Framework: 930. 개발자를 위한 닷넷 어셈블리 바인딩 - DEVPATH 환경 변수
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...