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

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

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




C# 14 - (2) 속성 구문에서 문맥 키워드로 추가되는 field 예약어

아래의 문서를 기준으로,

Working Set C#
; https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md#working-set-c

Proposal: field keyword in properties #140
; https://github.com/dotnet/csharplang/issues/140

2번째에 해당하는 "field-keyword"에 대한 설명입니다.

The field keyword
; https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-14#the-field-keyword

참고로, 현재(2025-07-18) 이번 글을 실습하려면 csproj 파일에 LangVersion을 preview로 설정해야 합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <LangVersion>preview</LangVersion>
    </PropertyGroup>

</Project>




C# 3부터 구현된 자동 속성 구문(Automatically implemented properties)은 그에 대응하는 필드를 사용자가 굳이 정의하지 않아도 컴파일러가 자동으로 생성해 주기 때문에 무척이나 편리했습니다. 즉, 원래는 이렇게 구현해야 했던 것을,

class Person
{
    // 자동 속성 구문을 사용하지 않는 경우
    int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }

    // ...[생략]...
}


단 한 줄의 코드로 간단하게 대체할 수 있었던 것입니다.

class Person
{
    public int Age { get; set; } // 자동 속성 구문
}

그런데, 만약 get/set 접근자에서 어떤 식으로든 값을 접근해야 한다면 어쩔 수 없이 자동 생성된 필드를 다시 정의하는 식으로 코드를 바꿔야만 했습니다. 가령 위의 코드에서 age 값에는 음수를 허용하고 싶지 않다면 그 조건을 걸기 위해 다음과 같이 코드를 바꿔야만 합니다.

int _age;

public int Age
{
    get => _age; // get 접근자에도 _age 필드를 사용해야 하고,
    set
    {   // set 접근자에서 _age 필드에 값을 할당하기 전에 조건을 설정
        if (value < 0)
        {
            throw new ArgumentOutOfRangeException("Age cannot be negative.");
        }

        _age = value;
    }
}

이런 불편함을 덜기 위해 field 예약어가 새롭게 추가되었는데요, 이 예약어는 get/set 접근자에서 자동 생성된 필드를 대표하게 돼, 이제 코드는 다음과 같이 간단하게 작성할 수 있습니다.

public int Age
{
    get; // get 접근자는 그대로 자동 생성 구문을 사용하고,
    set
    {
        if (value < 0)
        {
            throw new ArgumentOutOfRangeException("Age cannot be negative.");
        }

        // C# 컴파일러는 field 예약어를 자동 생성해 두었던 필드로 대체하는 코드로 변환
        field = value;
    }
}

사실 그다지 크게 중요한 구문은 아니지만, 은근 가려움을 긁어 주는 구문이 아닐까 싶습니다. ^^




참고로, field 예약어는 "문맥 키워드(contextual keyword)"이기 때문에 속성 접근자(get/set) 구문에서만 사용할 수 있습니다. 달리 말하면, 만약 기존 get/set 코드에서 "field"라는 이름의 변수를 사용하고 있었다면 C# 14부터는 컴파일 오류가 발생하므로 소스 코드의 "하위 호환성"이 깨지게 된 것입니다.

Expression field in a property accessor refers to synthesized backing field
; https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/breaking-changes/compiler%20breaking%20changes%20-%20dotnet%2010#expression-field-in-a-property-accessor-refers-to-synthesized-backing-field

Variable named field disallowed in a property accessor
; https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/breaking-changes/compiler%20breaking%20changes%20-%20dotnet%2010#variable-named-field-disallowed-in-a-property-accessor

예를 들어 C# 13까지는 다음과 같은 코드가 정상적으로 컴파일되었지만,

class Student
{
    int _age;

    public int Age
    {
        get
        {
            int field = 20; // C# 13까지는 "field"라는 이름의 변수를 사용 가능
            return _age + field;
        }
        set { this._age = value; }
    }
}

동일한 소스 코드를 C# 14로 컴파일하게 되면 오류가 발생하는 것입니다. 어쩔 수 없습니다, "field"가 이제 문맥 예약어로 바뀌었으므로 C#의 '@' 접두사를 이용해 예약어 변수가 아님을 명시적으로 표시하든가, 아예 이름을 바꾸는 식으로 코드를 변경해야 합니다.

class Student
{
    public int Age
    {
        get 
        {
            // 기존의 "field" 변수가 있었다면 '@' 접두사를 붙이거나, 아예 이름을 변경
            int @field = 20;
            return field + @field;
        }

        set { field = value; }
    }

    // ...[생략]...
}




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







[최초 등록일: ]
[최종 수정일: 7/18/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)
12414정성태11/18/202021971VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202020303.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202022285.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202018738오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202020132디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202021335.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202036398도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202021459.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202022317.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202021259.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202021879.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202019531.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202022320.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202021521VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202017447오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202020204.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202020909오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202020947.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202016739VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202020649오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202017996오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202016432오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202021115.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202022149디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202021129.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202019001오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...