I'm writing code that calls Excel macros via COM Automation. There is a need to handle different return types and pattern matching is perfect for that:
var result = ExcelApp.Run("MyMacro", ...);
return result switch
{
object[,] array => ...,
string message => ...,
_ => throw new MyException("...")
};
Because it's Excel the arrays have a lower bound of 1 instead of 0 and this is fully supported in .NET. However, to my surprise I have discovered that when I try to perform pattern matching of a one-dimensional array with a lower bound of 1 the pattern doesn't match.
To elaborate, creating a 2×2 array with lower bounds of 1 will match the pattern object[,]
, i.e. the following statement is true
:
Array.CreateInstance(typeof(object), new[] { 2, 2 }, new[] { 1, 1 }) is object[,] array
However, creating a 1×2 array (just a normal array with two elements) with a lower bound of 1 (which is not normal) will not match the pattern object[]
, i.e. the following statement is false
:
Array.CreateInstance(typeof(object), new[] { 2 }, new[] { 1 }) is object[] array
This is surprising to me but is there a pattern that can be used to match a one-dimensional array with a non-zero lower bound?