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

C# 8.0의 #nulable 관련 특성을 .NET Framework 프로젝트에서 사용하는 방법

C# 8.0의 신규 문법 중에서 .NET Core 3.0이 아닌 .NET Framework에서 사용할 수 없는 구문이 4가지입니다.

  1. 기본 인터페이스 메서드
  2. 비동기 스트림
  3. #nullable 지시자와 nullable 참조 형식
  4. 새로운 연산자 - 인덱스, 범위

이 중에서 1번은 .NET Core 3.0에서만 가능하고, 2번은 NuGet으로부터 System.Interactive.Async 어셈블리를 참조 추가하면 되고, 나머지 2개는 개발자가 타입을 정의해 주면 사용할 수 있습니다. 이 중에서 4번에 대해서는 설명한 적이 있는데,

C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법
; https://www.sysnet.pe.kr/2/0/11835

Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor'
; https://www.sysnet.pe.kr/2/0/11836

이번에는 3번에 대해서 설명하려고 합니다. ^^

우선 이를 위해 C# 8.0 컴파일러를 활성화하고,

.NET Framework 프로젝트에서 C# 8.0 컴파일러를 사용하는 방법
; https://www.sysnet.pe.kr/2/0/12033

소스 코드에 다음과 같이 null 체크에 대한 NotNullWhen 특성을 사용하면,

#nullable enable

using System.Diagnostics.CodeAnalysis;

class Program
{
    public string? Name = "";

    static void Main(string[] args)
    {
        Program pg = new Program();
        GetLengthOfName(pg);
    }

    static int GetLengthOfName(Program person)
    {
        /* IsNull 코드를 빼면, 그 아래의 person.Name.Length에서 null 참조 경고 발생 */
        if (IsNull(person.Name))
        {
            return 0;
        }

        return person.Name.Length;
    }

    static bool IsNull([NotNullWhen(false)] string? value)
    {
        if (value == null)
        {
            return true;
        }

        return false;
    }
}

NotNullWhen 타입(및 그 외 8개의 특성)이,

Update libraries to use nullable reference types and communicate nullable rules to callers
; https://learn.microsoft.com/en-us/dotnet/csharp/nullable-attributes

.NET Framework 4.8 BCL에는 포함되어 있지 않으므로 컴파일 오류가 발생합니다. 다행히 특성에 불과하기 때문에 다음과 같이 관련 타입들을 추가해 주면 .NET Framework 용 프로젝트에서도 사용할 수 있습니다.

// Attributes for nullable annotations
// https://github.com/dotnet/corefx/issues/37826

namespace System.Diagnostics.CodeAnalysis
{
    /// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)]
    public sealed class AllowNullAttribute : Attribute { }

    /// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)]
    public sealed class DisallowNullAttribute : Attribute { }

    /// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)]
    public sealed class MaybeNullAttribute : Attribute { }

    /// <summary>Specifies that an output will not be null even if the corresponding type allows it.</summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)]
    public sealed class NotNullAttribute : Attribute { }

    /// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter may be null even if the corresponding type disallows it.</summary>
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class MaybeNullWhenAttribute : Attribute
    {
        /// <summary>Initializes the attribute with the specified return value condition.</summary>
        /// <param name="returnValue">
        /// The return value condition. If the method returns this value, the associated parameter may be null.
        /// </param>
        public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

        /// <summary>Gets the return value condition.</summary>
        public bool ReturnValue { get; }
    }

    /// <summary>Specifies that when a method returns <see cref="ReturnValue"/>, the parameter will not be null even if the corresponding type allows it.</summary>
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
    public sealed class NotNullWhenAttribute : Attribute
    {
        /// <summary>Initializes the attribute with the specified return value condition.</summary>
        /// <param name="returnValue">
        /// The return value condition. If the method returns this value, the associated parameter will not be null.
        /// </param>
        public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;

        /// <summary>Gets the return value condition.</summary>
        public bool ReturnValue { get; }
    }

    /// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true)]
    public sealed class NotNullIfNotNullAttribute : Attribute
    {
        /// <summary>Initializes the attribute with the associated parameter name.</summary>
        /// <param name="parameterName">
        /// The associated parameter name.  The output will be non-null if the argument to the parameter specified is non-null.
        /// </param>
        public NotNullIfNotNullAttribute(string parameterName)
        {
            ParameterName = parameterName ?? throw new ArgumentNullException(nameof(parameterName));
        }

        /// <summary>Gets the associated parameter name.</summary>
        public string ParameterName { get; }
    }

    /// <summary>Applied to a method that will never return under any circumstance.</summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public sealed class DoesNotReturnAttribute : Attribute { }

    /// <summary>Specifies that the method will not return if the associated Boolean property is passed the specified value.</summary>
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true)]
    public sealed class DoesNotReturnIfAttribute : Attribute
    {
        /// <summary>Initializes the attribute.</summary>
        /// <param name="parameterValue">
        /// The condition parameter value.  Code after the method will be unreachable if the argument to the associated parameter
        /// matches this value.
        /// </param>
        public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;

        /// <summary>Gets the condition parameter value.</summary>
        public bool ParameterValue { get; }
    }
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 3/1/2023]

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

비밀번호

댓글 작성자
 



2021-01-24 08시16분
갈림길 인지 - nullable 참조 형식과 switch 식 [.NET Conf 2021 x Seoul - 42분 동영상]
; https://www.youtube.com/watch?v=g-SXdtF7k3c
정성태
2021-08-06 09시34분
How to Stop NullReferenceExceptions in .NET: Implementing Nullable Reference Types
; https://christianfindlay.com/2021/07/30/stop-nullreferenceexceptions/
정성태

... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13097정성태7/12/20225458오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228219.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226303Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20225994오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20226926.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227862.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226681.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225813오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226299개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225423개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228368스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227793.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227858.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226470개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227049.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226109.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226185.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226797개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224549오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226564.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226894스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225857Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226157.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226350Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226653Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227228스크립트: 39. Python에서 cx_Oracle 환경 구성
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...