C# 8.0 introduced nullable reference types. Since .NET 6 we are able to easily retreive nullability info through reflection.
Let's assume the following class.
class Person
{
public required string FirstName { get; init; }
public string? MiddleName { get; init; }
public required string LastName { get; init; }
}
To retreive nullability info we use the new NullabilityInfoContext.
// Program.cs - Top-level statements
var personType = typeof(Person);
var middleNameProperty = personType.GetProperty("MiddleName")!;
var nullabilityInfo = new NullabilityInfoContext().Create(middleNameProperty);
Assert.Equal(nullabilityInfo.ReadState, NullabilityState.Nullable);
That's it!