Home > Net >  How to get the Type of an Array of Nullable Primitive?
How to get the Type of an Array of Nullable Primitive?

Time:01-09

I have a property defined as:

public bool[] _array { get; set; }                  
public bool?[] _null_array { get; set; }            

I followed the instructions in How do I determine the underlying type of an array

foreach (var _property in typeof(T).GetProperties())
{ 
    var _propertyType = _property.PropertyType;
    var _propertyName = _property.Name;

    var CheckArray = _propertyType.IsArray;
    var UType      = _propertyType.GetElementType().Name;
    ....
}

The results for UType is:

_array      => "Boolean"
_null_array => "Nullable`1"

How do I get the type of an array of nullable primitive ?

Thanks.

CodePudding user response:

You already have it. The array element type is bool? aka Nullable<bool> aka Nullable``1 (only one backtick, blame markdown) with generic argument bool. If you're after bool, then you'll want Nullable.GetUnderlyingType on the element type; this returns null for things that aren't Nullable<T>, so consider:

var type = _propertyType.GetElementType();
type = Nullable.GetUnderylingType(type) ?? type;
var UType = type.Name;
  • Related