Bug with Array.CreateInstance() when lower bound > 0

G

Gianluca

If you create an array using Array.CreateInstance() and use a lower bound >
0, you apparently get an array of the wrong type.

int[] lenghts = new int[] {1};
int[] lowerBounds = new int[] {1};
string[] ar = (string[])Array.CreateInstance(typeof(string), lengths,
lowerBounds);

Throws an InvalidCastException because "string[*]" cannot be casted to
"string[]".

int[] lenghts = new int[] {1};
int[] lowerBounds = new int[] {0};
string[] ar = (string[])Array.CreateInstance(typeof(string), lengths,
lowerBounds);

This works fine. The only difference in the lower bound.

int[] lenghts = new int[] {1,1};
int[] lowerBounds = new int[] {1,1};
string[,] ar = (string[,])Array.CreateInstance(typeof(string), lengths,
lowerBounds);

Even this work fine. The difference is the number of dimensions. So the
problem cannot be just the lower bound > 0 because in this case (and with
more dimensions too) it works well.

Everything works well in .NET 1.1. So it's apparently a bug introduced in
..NET 2.0.

Has anyone seen this before? And what is "string[*]"?

Regards,
Gianluca
 
J

Jon Skeet [C# MVP]

Gianluca said:
If you create an array using Array.CreateInstance() and use a lower bound >
0, you apparently get an array of the wrong type.

Well, sort of.

Internally, .NET has two types of array - "vectors" (single-
dimensional, 0-based) and more general arrays.

When C# uses a single-dimensional array, it *assumes* it's one of these
"vector" types and that's what it really casts it to.

If you need to use a single-dimensional array with a non-zero lower
bound in C#, you need to access it using the Array class (and IList
etc).
Everything works well in .NET 1.1. So it's apparently a bug introduced in
.NET 2.0.

Hmm... I thought I'd seen exactly the same behaviour in 1.1...
unfortunately I can't easily test it any more.
 
G

Gianluca

Yep. I know about the internal difference between the vector and the array.
And you are right that it doesn't work with .NET 1.1 as well. I was testing
MD arrays and it also works if you cast it in the immediate window.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top