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;
}
}
static bool IsSingleDimensionalZeroBasedArray(Type type)
{
return type != null && type.IsArray && type == type.GetElementType().MakeArrayType();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With