Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I recognize a System.Type instance representing SZ-Array?

CLR uses distinct System.Type instances to represent SZ-arrays (Single-dimensional, Zero-based, aka vectors) and non-zero-based arrays (even if they are single-dimensional). I need a function that takes an instance of System.Type and recognizes if it represents a SZ-array. I was able to check the rank using GetArrayRank() method, but do not know how to check that it is zero-based. Would you please help me?

using System;

class Program
{
    static void Main()
    {
        var type1 = typeof (int[]);
        var type2 = Array.CreateInstance(typeof (int), new[] {1}, new[] {1}).GetType();

        Console.WriteLine(type1 == type2); // False

        Console.WriteLine(IsSingleDimensionalZeroBasedArray(type1));  // True
        Console.WriteLine(IsSingleDimensionalZeroBasedArray(type2)); //  This should be False
    }

    static bool IsSingleDimensionalZeroBasedArray(Type type)
    {
        // How do I fix this implementation?
        return type != null && type.IsArray && type.GetArrayRank() == 1;
    }
}
like image 462
Oksana Gimmel Avatar asked May 03 '13 00:05

Oksana Gimmel


1 Answers

static bool IsSingleDimensionalZeroBasedArray(Type type)
{
    return type != null && type.IsArray && type == type.GetElementType().MakeArrayType();
}
like image 190
Zakharia Stanley Avatar answered Nov 15 '22 15:11

Zakharia Stanley