Favicon

Null forgiving operator

Peponi11/18/20242m

C#
SyntaxOperator!

1. Introduction

Null-forgiving 연산자 (!) 는 단항 후위 연산자로, nullable 컨텍스트에서 null 경고를 억제한다. ! 연산자는 컴파일러의 분석에만 영향을 주며 런타임에 영향을 주지 않고 x! 식을 x로 해석한다.

2. Example

  • 다음 nullable 컨텍스트의 BarCS8618을 생성한다.

    #nullable enable
     
    public class Foo
    {
        public string Bar;       // CS8618
        public string? Baz;     // 경고 없음
    }
  • 다음 nullable 컨텍스트의 BarCS8618을 생성하지 않고, 생성자에서 null을 전달할 시 CS8625를 생성한다.

    #nullable enable
     
    public class Foo(string value)
    {
        public string Bar = value;
    }
    static void Main(string[] args)
    {
        Foo foo = new(null);    // CS8625
        Foo bar = new(null!);   // 경고 없음
    }
  • 코드 구성에 의해 null이 될 수 없지만, 컴파일러가 이를 인식할 수 없는 경우 ! 연산자를 이용해 역참조할 수 있다.

    static void Main(string[] args)
    {
        var foo = GetFoo();
        Console.WriteLine(foo.Bar);     // CS8602
        Console.WriteLine(foo!.Bar);    // 경고 없음
    }
     
    static Foo? GetFoo() => new Foo("foo");
  • 컴파일러가 인식할 수 없는 컨텍스트에서 null 허용 정적 분석 특성을 이용해 컴파일러에 null이 아님을 알릴 수 있다.

    static void Main(string[] args)
    {
        var foo = GetFoo();
        if (IsNotNull(foo))
        {
            Console.WriteLine(foo.Bar);     // NotNullWhen 특성을 제거하면 CS8602 발생
        }
    }
     
    static Foo? GetFoo() => new Foo("foo");
     
    // NotNullWhen 특성을 이용해 컴파일러에 null이 아님을 알림
    static bool IsNotNull([NotNullWhen(true)] Foo? foo) => true;

3. 참조 자료