Using Reflection how do you determine if a class property allows null?

25 views Asked by At

using the .Net framework 4.8 with c# 9.0 is there a way to detect if a "class" property can be assigned null using reflection?

public class Nested
{
    public string Test { get;set; } = "";
}

public class Test
{
    public int Number { get;set; } = 0;
    public int? Number2 { get;set; } = 0;

    public Nested Instance1 { get;set; } = new();
    public Nested? Instance2 { get;set; } = null;
}

public bool IsNullable(Type pPropertyType)
{
    return Nullable.GetUnderlyingType(pPropertyType) != null;
}

When I use reflection, only some of the types like Int? or DateTime? show as nullable.

 foreach (PropertyInfo pPropertyInfo in typeof(Test).GetProperties())
 {
     sw.WriteLine(pPropertyInfo.Name + " " + IsNullable(pPropertyInfo.PropertyType));
 }

The output I get using the method above:

  • Number False
  • Number2 True
  • Instance1 False
  • Instance2 False

How can I properly detect when a class property like Instance2 is marked with the nullable (?) and will allow nulls?

I am using the .Net framework 4.8 with c# 9.0.

0

There are 0 answers