jeudi 15 mars 2018

How can I observe the value type of an array?

I have a method that checks the Type of an object to determine if it is complex:

private static bool IsComplexObject(Type type)
{
    if (IsNullable(type))
    {
        // nullable type, check if the nested type is simple
        return IsComplexObject(type.GetGenericArguments()[0]);
    }

    if (type.Equals(typeof(string)))
    {
        return false;
    }
    if (type.Equals(typeof(decimal)))
    {
        return false;
    }
    if (type.Equals(typeof(DataTable)))
    {
        return false;
    }
    if (type.IsValueType)
    {
        return false;
    }
    if (type.IsPrimitive)
    {
        return false;
    }
    if (type.IsEnum)
    {
        return false;
    }

    return true;
}

The trouble is: when I have a Type of a simple type array, Int32[] for example, my method returns true.

I can prevent this from happening by adding this if statement into my method:

if (type.IsArray)
{
    return false;
}

The problem is that this if statement then prevents actual complex objects from being identified. For example, the following setup determines a custom class to not be complex:

public class TestClass
{ 
    public void TestComplexArray()
    {
        var result = IsComplexObject(typeof(MyComplexClass[]));

        // result == false
    }
}

public class MyComplexClass
{
    public string Name { get; set; }
    public string Id { get; set; }
}

So my question is: how can I check for the complexity of an array's value type to separate Int32[] from MyComplexClass[]?





Aucun commentaire:

Enregistrer un commentaire