1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C#】Null許容参照型かリフレクションで確認する方法

Last updated at Posted at 2023-11-18

概要

string? のようなNull許容かどうかを確認する方法を記述します。
System.Runtime.CompilerServices.NullableAttributeを使えば良いという記事を見かけますが、.NET 7ではinternalになっていて使えなくなっていたため最新の方法を調査しましたので記事にします。

コード

using System.Reflection;

static class TypeExtensions
{
    public static bool IsNullableReference(this PropertyInfo _this)
    {
        var nullabilityInfoContext = new NullabilityInfoContext();
        switch(nullabilityInfoContext.Create(_this).ReadState)
        {
            case NullabilityState.Nullable: 
                return true;
            case NullabilityState.NotNull:
                return false;
            default:
                throw new InvalidOperationException("Nullable reference must be enabled");
        }
    }
}

ちなみにNullabilityInfoContextをフィールドに置いて使い回したら例外が発生しました。毎回生成するのが正解のようです。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?