I am iterating the reflected properties of a type. I want to know which have been defined as nullable, and which are not. I believe the usual approach is:
Nullable.GetUnderlyingType(property.PropertyType) != null
I am using .NET 5.0 and opted into Nullable reference types. Unfortunately this always returns False
for both string
and string?
, whereas I expected the latter to be 'True'.
Project File
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
Type
public record MyRecord
(
string ANonNullableProperty,
string? ANullableProperty
);
Nullable Test
foreach (var property in typeof(MyRecord).GetProperties())
{
bool isNullable = Nullable.GetUnderlyingType(property.PropertyType) != null;
Console.WriteLine($"Property {property.Name} null: {isNullable}");
}
Expected Output
Property ANonNullableProperty null: False
Property ANullableProperty null: True
Actual Output
Property ANonNullableProperty null: False
Property ANullableProperty null: False
Is this a subtle defect, or have I misunderstood something? Is there a workaround or another way?
Aucun commentaire:
Enregistrer un commentaire