vendredi 23 avril 2021

Using reflection how can we tell if a class property is a nullable collection and get its data type?

I have no problems with properties that are non-nullable collections but everything changes when the property is a nullable collection...

Given a class with nullable collection properties (int?[], long?[], List<Nullable>, ...)

public class SomeClass
{
    public int?[] PropertyX { get; set; }
    public long?[] PropertyY { get; set; }
    public float?[] PropertyZ { get; set; }
    public List<decimal?> PropertyList { get; set; }
    public string Name { get; set; }
} 

How can I tell if the property is a nullable collection?
Does the nullable collection have any actual values?
Lastly what is the nullable collections data type?

public class SomeOtherClass
{
    public string Discover(SomeClass someClass)
    {
        var sb = new StringBuilder();
        foreach (var propertyInfo in someClass.GetType().GetProperties())
        {
            var propValue = propertyInfo.GetValue(someClass, new object[] { });
            if (propValue.IsNullableCollection() && propValue.HasValue())
            {
                sb.AppendFormat("{0} data type is {1}", propValue.GetDataType());
            }
        }
        return sb.ToString();
    }
}

Example:

void Main
{
  var sc = new SomeClass() 
  {
    PropertyX = new int?[2]{50,10}
  };
  var output = new SomeOtherClass().Discover(sc); 
  
  //Display Output ...
}

"PropertyX has values and data type is int."





Aucun commentaire:

Enregistrer un commentaire