Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Simple stuff, it seems like not possibile to cast long[] to object[]. Anyone knows why so?

What I have tried:

var array = (object[])Array.CreateInstance(typeof(long), 1);


System.InvalidCastException: Unable to cast object of type 'System.Int64[]' to type 'System.Object[]'.
Posted
Updated 27-Feb-21 9:04am
v2
Comments
[no name] 27-Feb-21 14:08pm    
Array covariance doesn’t apply to value types.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/
csrss 27-Feb-21 14:27pm    
Thx!

1 solution

You can't cast an array of values to any other array type because value types are "special": they aren't all the same size, and value types can't be inherited anyway.

With reference types, the variable is always the same size: 8 bytes on a 64 bit system, 4 bytes on a 32 bit. Value types can be anything between 1 byte (normally padded to a machine word boundary) and ... well, there is no absolute limit, but I'd suspect a practical limit of under 2MB as that is the default stack size for a .NET app.

Since the size of the elements isn't the same, you can't cast the array to a different type without resizing the actual elements, and that means reallocating the array and creating a new type for each element, then copying the data over. That isn't going to happen!

It may help if you see this: Using struct and class - what's that all about?[^] - it may help you unerstand the difference!
 
Share this answer
 
Comments
csrss 27-Feb-21 15:07pm    
Thx :)
OriginalGriff 27-Feb-21 16:21pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900