I want to know if a property type is a nullable reference type or not. I found several blog posts claiming that we can simply check the custom attributes by reflection. Given the class Foo:
public class Foo
{
public string Bar1 { get; set; }
public string? Bar2 { get; set; }
}
I make the following calls:
typeof(Foo).GetProperty("Bar1").CustomAttributes //returns an empty collection
typeof(Foo).GetProperty("Bar2").CustomAttributes //returns a collection with one instance of NullableAttribute
Weirdly, when I change the class to:
public class Foo
{
public string? Bar2 { get; set; }
}
Now, the CustomAttributes are empty.
typeof(Foo).GetProperty("Bar2").CustomAttributes //returns an empty collection
What is a reliable way to determine if a property type is a nullable reference?